package com.ys.service.finance.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ys.entity.business.TpAmazonSeller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.threeten.bp.OffsetDateTime;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.amazon.SellingPartnerAPIAA.LWAAuthorizationCredentials;
import com.ys.config.MyConfig;
import com.ys.entity.business.TpAmazonShop;
import com.ys.entity.business.TpAmazonShopProduct;
import com.ys.entity.finance.TcwFinancesApiData;
import com.ys.entity.finance.TcwFinancesApiInFo;
import com.ys.entity.finance.TcwFinancesApiInFoId;
import com.ys.entity.finance.TcwFinancesEventGroups;
import com.ys.entity.finance.TcwStoreAccount;
import com.ys.enume.AmazonSellerEnum;
import com.ys.enume.FinancialEventsType;
import com.ys.enume.RegionEnum;
import com.ys.mapper.business.DiySqlMapper;
import com.ys.mapper.finance.TcwFinancesEventGroupsMapper;
import com.ys.service.finance.TcwFinancesApiDataService;
import com.ys.service.log.ApiLogService;
import com.ys.util.dhecp.DateUtils;
import com.ys.vo.ApiResponse;
import com.ys.vo.R;

import io.swagger.client.api.DefaultApi;
import io.swagger.client.model.AdhocDisbursementEvent;
import io.swagger.client.model.AdjustmentEvent;
import io.swagger.client.model.AdjustmentItem;
import io.swagger.client.model.AffordabilityExpenseEvent;
import io.swagger.client.model.CapacityReservationBillingEvent;
import io.swagger.client.model.ChargeComponent;
import io.swagger.client.model.ChargeRefundEvent;
import io.swagger.client.model.ChargeRefundTransaction;
import io.swagger.client.model.CouponPaymentEvent;
import io.swagger.client.model.DebtRecoveryEvent;
import io.swagger.client.model.FBALiquidationEvent;
import io.swagger.client.model.FailedAdhocDisbursementEvent;
import io.swagger.client.model.FeeComponent;
import io.swagger.client.model.FinancialEventGroup;
import io.swagger.client.model.FinancialEventGroupList;
import io.swagger.client.model.FinancialEvents;
import io.swagger.client.model.ImagingServicesFeeEvent;
import io.swagger.client.model.ListFinancialEventGroupsPayload;
import io.swagger.client.model.ListFinancialEventGroupsResponse;
import io.swagger.client.model.ListFinancialEventsPayload;
import io.swagger.client.model.ListFinancialEventsResponse;
import io.swagger.client.model.LoanServicingEvent;
import io.swagger.client.model.NetworkComminglingTransactionEvent;
import io.swagger.client.model.PayWithAmazonEvent;
import io.swagger.client.model.ProductAdsPaymentEvent;
import io.swagger.client.model.RemovalShipmentAdjustmentEvent;
import io.swagger.client.model.RemovalShipmentEvent;
import io.swagger.client.model.RemovalShipmentItem;
import io.swagger.client.model.RemovalShipmentItemAdjustment;
import io.swagger.client.model.RentalTransactionEvent;
import io.swagger.client.model.RetrochargeEvent;
import io.swagger.client.model.SAFETReimbursementEvent;
import io.swagger.client.model.SAFETReimbursementItem;
import io.swagger.client.model.SellerDealPaymentEvent;
import io.swagger.client.model.SellerReviewEnrollmentPaymentEvent;
import io.swagger.client.model.ServiceFeeEvent;
import io.swagger.client.model.ShipmentEvent;
import io.swagger.client.model.ShipmentItem;
import io.swagger.client.model.SolutionProviderCreditEvent;
import io.swagger.client.model.TDSReimbursementEvent;
import io.swagger.client.model.TaxWithheldComponent;
import io.swagger.client.model.TaxWithholdingEvent;
import io.swagger.client.model.TrialShipmentEvent;
import io.swagger.client.model.ValueAddedServiceChargeEvent;

@Service("tcwFinancesApiDataService")
public class TcwFinancesApiDataServiceImpl  implements TcwFinancesApiDataService {

    private static Logger logger = LoggerFactory.getLogger(TcwFinancesApiDataServiceImpl.class);

    private Object lock = new Object();

    @Autowired
    private TcwFinancesEventGroupsMapper tcwFinancesEventGroupsMapper;

    @Autowired
    private DiySqlMapper diySqlMapper;

    @Autowired
    private ApiLogService apiLogService;

    public static Map<String, Integer> THREADF_MAP = new HashMap<String, Integer>() {{
        for (int i = 0; i < 50; i++) {
            put("threadAsin1" + i, 0);
        }
    }};


    @Override
    public ApiResponse getFinancesApi(JSONObject jsonObject, String startTimeStr, String endTimeStr) {
        logger.info("***********每月定时新增财务目录,店铺:"+jsonObject.get("sellerName").toString());
        ApiResponse apiResponse = new ApiResponse();

        LWAAuthorizationCredentials lwaAuthorizationCredentials = LWAAuthorizationCredentials.builder()
                .clientId(MyConfig.getAmazonLwaClientKey())
                .clientSecret(MyConfig.getAmazonLwaClientSecret())
                .refreshToken(jsonObject.get("refreshToken").toString())
                .endpoint(MyConfig.getAmazonLwaEndpoint())
                .build();

        DefaultApi api = new DefaultApi.Builder()
                .lwaAuthorizationCredentials(lwaAuthorizationCredentials)
                .endpoint(jsonObject.get("amazonServiceUrl").toString())
                .build();
        try {
            boolean isTrue = true;
            String nextToken = null;
            ListFinancialEventGroupsResponse listFinancialEventGroupsResponse;
            ListFinancialEventGroupsPayload listFinancialEventGroupsPayload;
            FinancialEventGroupList financialEventGroupList;
            ListFinancialEventsResponse listFinancialEventsResponse = null;
            ListFinancialEventsPayload payload;
            LocalDate endLocalDate;
            LocalDate endGroupLocalDate;
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
            List<TcwFinancesApiData> tcwFinancesApiDataList  = new ArrayList<>();
            FinancialEvents financialEvents1;
            List<FinancialEvents> financialEventsList;
            TcwFinancesEventGroups tcwFinancesEventGroups;
            List<TcwFinancesEventGroups> tcwFinancesEventGroupsList = new ArrayList<>();
            //每页最高100条，当token不为空需要再次请求
            while (isTrue) {
                //获取当前传入时间的财务事件
                listFinancialEventGroupsResponse =
                        api.listFinancialEventGroups(
                                null, OffsetDateTime.parse(endTimeStr), OffsetDateTime.parse(startTimeStr), nextToken);
                if (listFinancialEventGroupsResponse != null) {
                    listFinancialEventGroupsPayload = listFinancialEventGroupsResponse.getPayload();
                    //取出事件
                    financialEventGroupList = listFinancialEventGroupsPayload.getFinancialEventGroupList();
                    for (FinancialEventGroup financialEventGroup : financialEventGroupList) {
                        //ProcessingStatus = Closed  财务事件组的处理状态指示财务事件组的余额是否已结算。
                        if (!financialEventGroup.getProcessingStatus().equals("Closed")) {
                            continue;
                        }
                        //FundTransferStatus  	资金转账的状态 Failed 失败 Succeeded 成功 。
                        endLocalDate = dateFormat.parse(endTimeStr).toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                        endGroupLocalDate = dateFormat.parse(financialEventGroup.getFinancialEventGroupEnd()).toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                        if (endLocalDate.getMonthValue() == endGroupLocalDate.getMonthValue() && endGroupLocalDate.getYear() == endLocalDate.getYear()) {
                            if (financialEventGroup.getProcessingStatus() != null && financialEventGroup.getFundTransferStatus() != null) {
                                if (financialEventGroup.getProcessingStatus().equals("Closed") && financialEventGroup.getFundTransferStatus().equals("Succeeded")) {
                                    //当originalTotal有值,存入类型为Transfer的数据
                                    if (financialEventGroup.getOriginalTotal() == null) {
                                        continue;
                                    }

                                    tcwFinancesEventGroups =  new TcwFinancesEventGroups()
                                            .where("A.FinancialEventGroupId = '" + financialEventGroup.getFinancialEventGroupId() + "' AND A.AStatus = '匹配成功'")
                                            .queryFirst();
                                    if (tcwFinancesEventGroups != null){
                                        continue;
                                    }else {
                                        diySqlMapper.deleteFinancesEGid(financialEventGroup.getFinancialEventGroupId());
                                        diySqlMapper.deleteFinancesEventGroups(financialEventGroup.getFinancialEventGroupId());
                                    }

                                    //新增财务事件
                                    tcwFinancesEventGroups = new TcwFinancesEventGroups();
                                    tcwFinancesEventGroups.setFinancialEventGroupId(financialEventGroup.getFinancialEventGroupId());
                                    tcwFinancesEventGroups.setCurrencyCode(financialEventGroup.getOriginalTotal().getCurrencyCode());
                                    tcwFinancesEventGroups.setRegionCode(jsonObject.get("regionCode").toString());
                                    tcwFinancesEventGroups.setShopName(jsonObject.get("vgsjc").toString());
                                    tcwFinancesEventGroups.setCompanyID(jsonObject.get("vgsbm").toString());
                                    tcwFinancesEventGroups.setStartDate(dateFormat.parse(financialEventGroup.getFinancialEventGroupStart()));
                                    tcwFinancesEventGroups.setEndDate(dateFormat.parse(financialEventGroup.getFinancialEventGroupEnd()));
                                    tcwFinancesEventGroups.setCurrencyAmount(financialEventGroup.getOriginalTotal().getCurrencyAmount());
                                    if (financialEventGroup.getConvertedTotal() == null){
                                        tcwFinancesEventGroups.setConvertedTotal(financialEventGroup.getOriginalTotal().getCurrencyAmount());
                                        tcwFinancesEventGroups.setCurrency(financialEventGroup.getOriginalTotal().getCurrencyCode());
                                    }else {
                                        tcwFinancesEventGroups.setConvertedTotal(financialEventGroup.getConvertedTotal().getCurrencyAmount());
                                        tcwFinancesEventGroups.setCurrency(financialEventGroup.getConvertedTotal().getCurrencyCode());
                                    }
                                    tcwFinancesEventGroups.setXjCurrencyAmount(BigDecimal.ZERO);
                                    tcwFinancesEventGroups.setReserveDebit(BigDecimal.ZERO);
                                    tcwFinancesEventGroups.setReserveCredit(BigDecimal.ZERO);
                                    tcwFinancesEventGroups.setTwoCurrencyAmount(BigDecimal.ZERO);
                                    tcwFinancesEventGroups.setAStatus("无");
                                    tcwFinancesEventGroupsMapper.insert(tcwFinancesEventGroups);

                                    //事件回填金额
                                    addTcwF(tcwFinancesApiDataList, "Transfer", "Transfer","Transfer",
                                            null,0,financialEventGroup.getOriginalTotal().getCurrencyAmount(),
                                            financialEventGroup.getFinancialEventGroupId(),
                                            null, dateFormat.parse(financialEventGroup.getFundTransferDate()),null,tcwFinancesEventGroups);
                                    //上周期欠费金额
                                    if (financialEventGroup.getBeginningBalance() != null){
                                        if (financialEventGroup.getBeginningBalance().getCurrencyAmount().compareTo(BigDecimal.ZERO) != 0){
                                            addTcwF(tcwFinancesApiDataList, "BeginningBalance", "BeginningBalance","BeginningBalance",
                                                    null,0,financialEventGroup.getBeginningBalance().getCurrencyAmount(),
                                                    financialEventGroup.getFinancialEventGroupId(),
                                                    null, dateFormat.parse(financialEventGroup.getFundTransferDate()),null,tcwFinancesEventGroups);
                                        }
                                    }

                                    isTrue = true;
                                    nextToken = null;
                                    financialEventsList = new ArrayList<>();
                                    while (isTrue) {
                                        try{
                                            listFinancialEventsResponse =
                                                    api.listFinancialEventsByGroupId(financialEventGroup.getFinancialEventGroupId(), null, null,null,nextToken);
                                        }catch (Exception e){
                                            if (e.getMessage().equals("Too Many Requests")){
                                                Thread.sleep(1000L);
                                                continue;
                                            }else {
                                                apiResponse.setCode(500);
                                                apiResponse.setMessage("ECP_API定时获取亚马逊财务事件信息出错，具体错误信息为："+e.getMessage());
                                            }
                                        }

                                        payload = listFinancialEventsResponse.getPayload();
                                        if (payload.getFinancialEvents() != null) {
                                            financialEvents1 = payload.getFinancialEvents();
                                            financialEventsList.add(financialEvents1);
                                        }
                                        if (payload.getNextToken() != null) {
                                            nextToken = payload.getNextToken();
//                                            Thread.sleep(1000L);
                                        } else {
                                            isTrue = false;
                                        }
                                    }
                                    for (FinancialEvents financialEvents : financialEventsList){
                                        //ShipmentEventList 订单事件
                                        if (financialEvents.getShipmentEventList()  != null) {
                                            for (ShipmentEvent shipmentEvent : financialEvents.getShipmentEventList()) {
                                                addShipmentEventOrAdjustment(tcwFinancesApiDataList,shipmentEvent,tcwFinancesEventGroups,financialEventGroup,dateFormat.parse(shipmentEvent.getPostedDate()),FinancialEventsType.SHIPMENTEVENTLIST.getCode());
                                            }
                                        }
                                        //装运结算事件列表
                                        if (financialEvents.getShipmentSettleEventList()  != null) {
                                            for (ShipmentEvent shipmentEvent : financialEvents.getShipmentSettleEventList()) {
                                                addShipmentEventOrAdjustment(tcwFinancesApiDataList,shipmentEvent,tcwFinancesEventGroups,financialEventGroup,dateFormat.parse(shipmentEvent.getPostedDate()),FinancialEventsType.SHIPMENTSETTLEEVENTLIST.getCode());
                                            }
                                        }
                                        //退款事件列表
                                        if (financialEvents.getRefundEventList() != null) {
                                            for (ShipmentEvent shipmentEvent : financialEvents.getRefundEventList()) {
                                                addShipmentEventOrAdjustment(tcwFinancesApiDataList,shipmentEvent,tcwFinancesEventGroups,financialEventGroup,dateFormat.parse(shipmentEvent.getPostedDate()),FinancialEventsType.REFUNDEVENTLIST.getCode());
                                            }
                                        }
                                        //保证索赔事件列表
                                        if (financialEvents.getGuaranteeClaimEventList().size() != 0) {
                                            for (ShipmentEvent shipmentEvent : financialEvents.getGuaranteeClaimEventList()) {
                                                addShipmentEventOrAdjustment(tcwFinancesApiDataList,shipmentEvent,tcwFinancesEventGroups,financialEventGroup,dateFormat.parse(shipmentEvent.getPostedDate()),FinancialEventsType.GUARANTEECLAIMEVENTLIST.getCode());
                                            }
                                        }
                                        //退款事件列表
                                        if (financialEvents.getChargebackEventList().size() != 0) {
                                            for (ShipmentEvent shipmentEvent : financialEvents.getChargebackEventList()) {
                                                addShipmentEventOrAdjustment(tcwFinancesApiDataList,shipmentEvent,tcwFinancesEventGroups,financialEventGroup,dateFormat.parse(shipmentEvent.getPostedDate()),FinancialEventsType.CHARGEBACKEVENTLIST.getCode());
                                            }
                                        }
                                        //与卖家的 Pay with Amazon 账户相关的事件列表
                                        if (financialEvents.getPayWithAmazonEventList().size() != 0) {
                                            for (PayWithAmazonEvent payWithAmazonEvent : financialEvents.getPayWithAmazonEventList()){
                                                if (payWithAmazonEvent.getCharge() != null){
                                                    addTcwF(tcwFinancesApiDataList, FinancialEventsType.PAYWITHAMAZONEVENTLIST.getCode(), "Charge",payWithAmazonEvent.getCharge().getChargeType(), null,0,payWithAmazonEvent.getCharge().getChargeAmount().getCurrencyAmount(),
                                                            financialEventGroup.getFinancialEventGroupId(),  payWithAmazonEvent.getSellerOrderId(), dateFormat.parse(payWithAmazonEvent.getTransactionPostedDate()),null,tcwFinancesEventGroups);
                                                }

                                                if (payWithAmazonEvent.getFeeList() != null){
                                                    for (FeeComponent feeComponent:payWithAmazonEvent.getFeeList()){
                                                        addTcwF(tcwFinancesApiDataList, FinancialEventsType.PAYWITHAMAZONEVENTLIST.getCode(),"FeeList",feeComponent.getFeeType(), null,0,feeComponent.getFeeAmount().getCurrencyAmount(),
                                                                financialEventGroup.getFinancialEventGroupId(), payWithAmazonEvent.getSellerOrderId(), dateFormat.parse(payWithAmazonEvent.getTransactionPostedDate()),null,tcwFinancesEventGroups);
                                                    }
                                                }
                                            }
                                        }
                                        //有关解决方案提供商信用的信息列表。
                                        if (financialEvents.getServiceProviderCreditEventList().size() != 0) {
                                            for (SolutionProviderCreditEvent solutionProviderCreditEvent : financialEvents.getServiceProviderCreditEventList()) {
                                                addTcwF(tcwFinancesApiDataList, FinancialEventsType.SERVICEPROVIDERCREDITEVENTLIST.getCode(),"TransactionAmount",solutionProviderCreditEvent.getProviderTransactionType(), null,0,solutionProviderCreditEvent.getTransactionAmount().getCurrencyAmount(),
                                                        financialEventGroup.getFinancialEventGroupId(),  solutionProviderCreditEvent.getSellerOrderId(), dateFormat.parse(solutionProviderCreditEvent.getTransactionCreationDate()),null,tcwFinancesEventGroups);
                                            }
                                        }
                                        //有关 Retrocharge 或 RetrochargeReversal 事件的信息列表。
                                        if (financialEvents.getRetrochargeEventList() != null) {
                                            for (RetrochargeEvent retrochargeEvent : financialEvents.getRetrochargeEventList()) {
                                                //Base Tax
                                                addTcwF(tcwFinancesApiDataList, FinancialEventsType.RETROCHARGEEVENTLIST.getCode(),"BaseTax","Retrocharge", null,0,retrochargeEvent.getBaseTax().getCurrencyAmount(),
                                                        financialEventGroup.getFinancialEventGroupId(), retrochargeEvent.getAmazonOrderId(), dateFormat.parse(retrochargeEvent.getPostedDate()),null,tcwFinancesEventGroups);
                                                //ShippingTax
                                                addTcwF(tcwFinancesApiDataList, FinancialEventsType.RETROCHARGEEVENTLIST.getCode(),"ShippingTax","Retrocharge", null,0,retrochargeEvent.getShippingTax().getCurrencyAmount(),
                                                        financialEventGroup.getFinancialEventGroupId(), retrochargeEvent.getAmazonOrderId(), dateFormat.parse(retrochargeEvent.getPostedDate()),null,tcwFinancesEventGroups);
                                                //MarketplaceFacilitator
                                                BigDecimal markAmount = BigDecimal.ZERO;
                                                for (TaxWithheldComponent taxWithheldComponent : retrochargeEvent.getRetrochargeTaxWithheldList()) {
                                                    if (taxWithheldComponent.getTaxCollectionModel().equals("MarketplaceFacilitator")) {
                                                        for (ChargeComponent chargeComponent : taxWithheldComponent.getTaxesWithheld()) {
                                                            markAmount = markAmount.add(chargeComponent.getChargeAmount().getCurrencyAmount());
                                                        }
                                                    }
                                                }
                                                addTcwF(tcwFinancesApiDataList, FinancialEventsType.RETROCHARGEEVENTLIST.getCode(),"RetrochargeTaxWithheldList","MarketplaceFacilitator", null,0,markAmount,
                                                        financialEventGroup.getFinancialEventGroupId(), retrochargeEvent.getAmazonOrderId(), dateFormat.parse(retrochargeEvent.getPostedDate()), String.valueOf(retrochargeEvent.getRetrochargeTaxWithheldList()),tcwFinancesEventGroups);
                                            }
                                        }
                                        //RentalTransactionEventList 租赁交易事件信息列表。
                                        if (financialEvents.getRentalTransactionEventList() != null) {
                                            for (RentalTransactionEvent rentalTransactionEvent : financialEvents.getRentalTransactionEventList()) {
                                                //RentalChargeList 与租赁活动相关的费用列表
                                                for (ChargeComponent chargeComponent : rentalTransactionEvent.getRentalChargeList()){
                                                    addTcwF(tcwFinancesApiDataList, FinancialEventsType.RENTALTRANSACTIONEVENTLIST.getCode(),"RentalChargeList",chargeComponent.getChargeType(), null,0,chargeComponent.getChargeAmount().getCurrencyAmount(),
                                                            financialEventGroup.getFinancialEventGroupId(),  rentalTransactionEvent.getAmazonOrderId(), dateFormat.parse(rentalTransactionEvent.getPostedDate()),null,tcwFinancesEventGroups);
                                                }
                                                //RentalFeeList 与租赁活动相关的费用列表。
                                                for (FeeComponent feeComponent : rentalTransactionEvent.getRentalFeeList()) {
                                                    addTcwF(tcwFinancesApiDataList, FinancialEventsType.RENTALTRANSACTIONEVENTLIST.getCode(),"RentalFeeList",
                                                            feeComponent.getFeeType(), null, 0, feeComponent.getFeeAmount().getCurrencyAmount(),
                                                            financialEventGroup.getFinancialEventGroupId(),
                                                            rentalTransactionEvent.getAmazonOrderId(), dateFormat.parse(rentalTransactionEvent.getPostedDate()),null,tcwFinancesEventGroups);
                                                }
                                                //RentalInitialValue 客户最初为租赁该物品支付的金额
                                                if (rentalTransactionEvent.getRentalInitialValue() != null) {
                                                    addTcwF(tcwFinancesApiDataList, FinancialEventsType.RENTALTRANSACTIONEVENTLIST.getCode(),"RentalInitialValue",
                                                            "RentalInitialValue", null, 0, rentalTransactionEvent.getRentalInitialValue().getCurrencyAmount(),
                                                            financialEventGroup.getFinancialEventGroupId(),
                                                            rentalTransactionEvent.getAmazonOrderId(), dateFormat.parse(financialEventGroup.getFundTransferDate()),null,tcwFinancesEventGroups);
                                                }
                                                //RentalReimbursement  亚马逊向卖家支付的金额，用于补偿丢失的商品或失败的费用
                                                if (rentalTransactionEvent.getRentalReimbursement() != null) {
                                                    addTcwF(tcwFinancesApiDataList, FinancialEventsType.RENTALTRANSACTIONEVENTLIST.getCode(), "RentalReimbursement",
                                                            "RentalReimbursement", null, 0, rentalTransactionEvent.getRentalReimbursement().getCurrencyAmount(),
                                                            financialEventGroup.getFinancialEventGroupId(), rentalTransactionEvent.getAmazonOrderId(),
                                                            dateFormat.parse(financialEventGroup.getFundTransferDate()),null,tcwFinancesEventGroups);
                                                }
                                                //RentalTaxWithheldList 租赁物品的预扣税信息列表
                                                for (TaxWithheldComponent taxWithheldComponent : rentalTransactionEvent.getRentalTaxWithheldList()) {
                                                    for (ChargeComponent chargeComponent : taxWithheldComponent.getTaxesWithheld()) {
                                                        addTcwF(tcwFinancesApiDataList, FinancialEventsType.RENTALTRANSACTIONEVENTLIST.getCode(), "RentalTaxWithheldList",
                                                                chargeComponent.getChargeType(), null, 0, chargeComponent.getChargeAmount().getCurrencyAmount(),
                                                                financialEventGroup.getFinancialEventGroupId(),
                                                                rentalTransactionEvent.getAmazonOrderId(), dateFormat.parse(financialEventGroup.getFundTransferDate()),null,tcwFinancesEventGroups);
                                                    }
                                                }
                                            }
                                        }
                                        //ProductAdsPaymentEventList  赞助产品付款活动列表
                                        if (financialEvents.getProductAdsPaymentEventList() != null) {
                                            for (ProductAdsPaymentEvent productAdsPaymentEvent : financialEvents.getProductAdsPaymentEventList()) {
                                                //baseValue
                                                addTcwF(tcwFinancesApiDataList, FinancialEventsType.PRODUCTADSPAYMENTEVENTLIST.getCode(), "baseValue","baseValue", null, 0, productAdsPaymentEvent.getBaseValue().getCurrencyAmount(),
                                                        financialEventGroup.getFinancialEventGroupId(), null, dateFormat.parse(productAdsPaymentEvent.getPostedDate()),
                                                        "transactionValue:" + productAdsPaymentEvent.getTransactionValue().getCurrencyAmount(),tcwFinancesEventGroups);
                                                //taxValue
                                                addTcwF(tcwFinancesApiDataList, FinancialEventsType.PRODUCTADSPAYMENTEVENTLIST.getCode(),"taxValue", "taxValue", null, 0, productAdsPaymentEvent.getTaxValue().getCurrencyAmount(),
                                                        financialEventGroup.getFinancialEventGroupId(), null, dateFormat.parse(productAdsPaymentEvent.getPostedDate()),
                                                        "transactionValue:" + productAdsPaymentEvent.getTransactionValue().getCurrencyAmount(),tcwFinancesEventGroups);
                                            }
                                        }
                                        //ServiceFeeEventList 有关服务费事件的信息列表
                                        if (financialEvents.getServiceFeeEventList() != null) {
                                            for (ServiceFeeEvent serviceFeeEvent : financialEvents.getServiceFeeEventList()) {
                                                if (serviceFeeEvent.getFeeList() != null) {
                                                    for (FeeComponent feeComponent : serviceFeeEvent.getFeeList()) {
                                                        addTcwF(tcwFinancesApiDataList, FinancialEventsType.SERVICEFEEEVENTLIST.getCode(),"FeeList",
                                                                feeComponent.getFeeType(), serviceFeeEvent.getSellerSKU(), 0, feeComponent.getFeeAmount().getCurrencyAmount(),
                                                                financialEventGroup.getFinancialEventGroupId(),
                                                                serviceFeeEvent.getAmazonOrderId(), dateFormat.parse(financialEventGroup.getFundTransferDate()),null,tcwFinancesEventGroups);
                                                    }
                                                }
                                            }
                                        }
                                        //SellerDealPaymentEventList 交易相关费用的支付事件列表
                                        if (financialEvents.getSellerDealPaymentEventList() != null) {
                                            for (SellerDealPaymentEvent sellerDealPaymentEvent : financialEvents.getSellerDealPaymentEventList()) {
                                                addTcwF(tcwFinancesApiDataList, FinancialEventsType.SELLERDEALPAYMENTEVENTLIST.getCode(),"totalAmount",
                                                        sellerDealPaymentEvent.getFeeType(), null, 0, sellerDealPaymentEvent.getTotalAmount().getCurrencyAmount(),
                                                        financialEventGroup.getFinancialEventGroupId(),
                                                        null, dateFormat.parse(sellerDealPaymentEvent.getPostedDate()), String.valueOf(sellerDealPaymentEvent),tcwFinancesEventGroups);
                                            }
                                        }
                                        //DebtRecoveryEventList 债务追收事件信息列表。
                                        if (financialEvents.getDebtRecoveryEventList() != null) {
                                            for (DebtRecoveryEvent debtRecoveryEvent : financialEvents.getDebtRecoveryEventList()) {
                                                //RecoveryAmount
                                                if (debtRecoveryEvent.getRecoveryAmount() != null){
                                                    addTcwF(tcwFinancesApiDataList, FinancialEventsType.DEBTRECOVERYEVENTLIST.getCode(),"RecoveryAmount",
                                                            debtRecoveryEvent.getDebtRecoveryType(), null, 0, debtRecoveryEvent.getRecoveryAmount().getCurrencyAmount(),
                                                            financialEventGroup.getFinancialEventGroupId(), null,
                                                            dateFormat.parse(financialEventGroup.getFinancialEventGroupEnd()),null,tcwFinancesEventGroups);
                                                }
                                                //OverPaymentCredit
                                                if (debtRecoveryEvent.getOverPaymentCredit() != null){
                                                    addTcwF(tcwFinancesApiDataList, FinancialEventsType.DEBTRECOVERYEVENTLIST.getCode(),"OverPaymentCredit",
                                                            debtRecoveryEvent.getDebtRecoveryType(), null, 0, debtRecoveryEvent.getOverPaymentCredit().getCurrencyAmount(),
                                                            financialEventGroup.getFinancialEventGroupId(), null,
                                                            dateFormat.parse(financialEventGroup.getFinancialEventGroupEnd()),null,tcwFinancesEventGroups);
                                                }
                                            }
                                        }
                                        //LoanServicingEventList 贷款服务事件列表
                                        if (financialEvents.getLoanServicingEventList() != null) {
                                            for (LoanServicingEvent loanServicingEvent : financialEvents.getLoanServicingEventList()) {
                                                addTcwF(tcwFinancesApiDataList, FinancialEventsType.LOANSERVICINGEVENTLIST.getCode(),"LoanAmount"
                                                        ,loanServicingEvent.getSourceBusinessEventType(), null, 0, loanServicingEvent.getLoanAmount().getCurrencyAmount(),
                                                        financialEventGroup.getFinancialEventGroupId(),
                                                        null, dateFormat.parse(financialEventGroup.getFinancialEventGroupEnd()),null,tcwFinancesEventGroups);
                                            }
                                        }
                                        //AdjustmentEventList 卖家账户的调整事件信息列表
                                        if (financialEvents.getAdjustmentEventList() != null) {
                                            for (AdjustmentEvent adjustmentEvent : financialEvents.getAdjustmentEventList()) {
                                                if (adjustmentEvent.getAdjustmentItemList() != null){
                                                    for (AdjustmentItem adjustmentItem : adjustmentEvent.getAdjustmentItemList()) {
                                                        //AdjustmentItemList
                                                        addTcwF(tcwFinancesApiDataList, FinancialEventsType.ADJUSTMENTEVENTLIST.getCode(),"AdjustmentItemList",
                                                                adjustmentEvent.getAdjustmentType(), adjustmentItem.getSellerSKU(), Integer.valueOf(adjustmentItem.getQuantity()), adjustmentItem.getTotalAmount().getCurrencyAmount(),
                                                                financialEventGroup.getFinancialEventGroupId(),
                                                                null, dateFormat.parse(adjustmentEvent.getPostedDate()), String.valueOf(adjustmentEvent.getAdjustmentAmount()),tcwFinancesEventGroups);
                                                    }
                                                }else {
                                                    if (adjustmentEvent.getAdjustmentAmount() != null){
                                                        if ("ReserveCredit".equals(adjustmentEvent.getAdjustmentType())){
                                                            tcwFinancesEventGroups.setReserveCredit(adjustmentEvent.getAdjustmentAmount().getCurrencyAmount());
                                                        }
                                                        if ("ReserveDebit".equals(adjustmentEvent.getAdjustmentType())){
                                                            tcwFinancesEventGroups.setReserveDebit(adjustmentEvent.getAdjustmentAmount().getCurrencyAmount());
                                                        }
                                                        addTcwF(tcwFinancesApiDataList, FinancialEventsType.ADJUSTMENTEVENTLIST.getCode(),"AdjustmentAmount",
                                                                adjustmentEvent.getAdjustmentType(), null, 0, adjustmentEvent.getAdjustmentAmount().getCurrencyAmount(),
                                                                financialEventGroup.getFinancialEventGroupId(),
                                                                null, dateFormat.parse(adjustmentEvent.getPostedDate()), String.valueOf(adjustmentEvent.getAdjustmentAmount()),tcwFinancesEventGroups);
                                                    }
                                                }
                                            }
                                        }
                                        //SAFETReimbursementEventList SAFET 报销事件列表
                                        if (financialEvents.getSaFETReimbursementEventList() != null) {
                                            for (SAFETReimbursementEvent safetReimbursementEvent : financialEvents.getSaFETReimbursementEventList()) {
                                                for (SAFETReimbursementItem safetReimbursementItem : safetReimbursementEvent.getSaFETReimbursementItemList()) {
                                                    for (ChargeComponent chargeComponent : safetReimbursementItem.getItemChargeList()) {
                                                        addTcwF(tcwFinancesApiDataList, FinancialEventsType.SAFETREIMBURSEMENTEVENTLIST.getCode(), "SAFETReimbursementItemList",
                                                                chargeComponent.getChargeType(), null, Integer.valueOf(safetReimbursementItem.getQuantity()), safetReimbursementEvent.getReimbursedAmount().getCurrencyAmount(),
                                                                financialEventGroup.getFinancialEventGroupId(), null, dateFormat.parse(safetReimbursementEvent.getPostedDate())
                                                                ,String.valueOf(safetReimbursementEvent.getReimbursedAmount()),tcwFinancesEventGroups);
                                                    }
                                                }
                                            }
                                        }
                                        //SellerReviewEnrollmentPaymentEventList 有关早期审稿人计划费用事件的信息列表。
                                        if (financialEvents.getSellerReviewEnrollmentPaymentEventList() != null) {
                                            for (SellerReviewEnrollmentPaymentEvent sellerReviewEnrollmentPaymentEvent : financialEvents.getSellerReviewEnrollmentPaymentEventList()) {
                                                //ChargeComponent
                                                addTcwF(tcwFinancesApiDataList, FinancialEventsType.SELLERREVIEWENROLLMENTPAYMENTEVENTLIST.getCode(), "ChargeComponent",sellerReviewEnrollmentPaymentEvent.getChargeComponent().getChargeType(),
                                                        null, 0, sellerReviewEnrollmentPaymentEvent.getChargeComponent().getChargeAmount().getCurrencyAmount(),
                                                        financialEventGroup.getFinancialEventGroupId(), null,
                                                        dateFormat.parse(sellerReviewEnrollmentPaymentEvent.getPostedDate()),null,tcwFinancesEventGroups);
                                                //FeeComponent
                                                addTcwF(tcwFinancesApiDataList, FinancialEventsType.SELLERREVIEWENROLLMENTPAYMENTEVENTLIST.getCode(), "FeeComponent",
                                                        sellerReviewEnrollmentPaymentEvent.getFeeComponent().getFeeType(),
                                                        null, 0, sellerReviewEnrollmentPaymentEvent.getFeeComponent().getFeeAmount().getCurrencyAmount(),
                                                        financialEventGroup.getFinancialEventGroupId(), null,
                                                        dateFormat.parse(sellerReviewEnrollmentPaymentEvent.getPostedDate()),null,tcwFinancesEventGroups);
                                                //TotalAmount
                                                addTcwF(tcwFinancesApiDataList, FinancialEventsType.SELLERREVIEWENROLLMENTPAYMENTEVENTLIST.getCode(), "TotalAmount",
                                                        sellerReviewEnrollmentPaymentEvent.getFeeComponent().getFeeType(),
                                                        null, 0, sellerReviewEnrollmentPaymentEvent.getTotalAmount().getCurrencyAmount(),
                                                        financialEventGroup.getFinancialEventGroupId(),  null,
                                                        dateFormat.parse(sellerReviewEnrollmentPaymentEvent.getPostedDate()),null,tcwFinancesEventGroups);
                                            }
                                        }
                                        //FBALiquidationEventList FBA库存清算付款事件列表
                                        if (financialEvents.getFbALiquidationEventList() != null) {
                                            for (FBALiquidationEvent fbaLiquidationEvent : financialEvents.getFbALiquidationEventList()) {
                                                //LiquidationProceedsAmount
                                                addTcwF(tcwFinancesApiDataList, FinancialEventsType.FBALIQUIDATIONEVENTLIST.getCode(), "LiquidationProceedsAmount",
                                                        "LiquidationProceedsAmount", null, 0, fbaLiquidationEvent.getLiquidationProceedsAmount().getCurrencyAmount(),
                                                        financialEventGroup.getFinancialEventGroupId(),
                                                        fbaLiquidationEvent.getOriginalRemovalOrderId(), dateFormat.parse(fbaLiquidationEvent.getPostedDate()),null,tcwFinancesEventGroups);
                                                //LiquidationFeeAmount
                                                addTcwF(tcwFinancesApiDataList, FinancialEventsType.FBALIQUIDATIONEVENTLIST.getCode(), "LiquidationFeeAmount",
                                                        "LiquidationFeeAmount", null, 0, fbaLiquidationEvent.getLiquidationFeeAmount().getCurrencyAmount(),
                                                        financialEventGroup.getFinancialEventGroupId(),
                                                        fbaLiquidationEvent.getOriginalRemovalOrderId(), dateFormat.parse(fbaLiquidationEvent.getPostedDate()),null,tcwFinancesEventGroups);

                                            }
                                        }
                                        //CouponPaymentEventList  优惠券支付事件信息列表
                                        if (financialEvents.getCouponPaymentEventList() != null) {
                                            for (CouponPaymentEvent couponPaymentEvent : financialEvents.getCouponPaymentEventList()) {
                                                //TotalAmount
                                                if (couponPaymentEvent.getTotalAmount() != null){
                                                    addTcwF(tcwFinancesApiDataList, FinancialEventsType.COUPONPAYMENTEVENTLIST.getCode(), "TotalAmount",
                                                            couponPaymentEvent.getFeeComponent().getFeeType(),
                                                            null, 0, couponPaymentEvent.getTotalAmount().getCurrencyAmount(),
                                                            financialEventGroup.getFinancialEventGroupId(), null,
                                                            dateFormat.parse(couponPaymentEvent.getPostedDate()),"TotalAmount:"+couponPaymentEvent.getTotalAmount().getCurrencyAmount(),tcwFinancesEventGroups);
                                                }
                                            }
                                        }
                                        //ImagingServicesFeeEventList 与 Amazon Imaging 服务相关的费用事件列表。
                                        if (financialEvents.getImagingServicesFeeEventList() != null) {
                                            for (ImagingServicesFeeEvent imagingServicesFeeEvent : financialEvents.getImagingServicesFeeEventList()) {
                                                if (imagingServicesFeeEvent.getFeeList() != null) {
                                                    for (FeeComponent feeComponent : imagingServicesFeeEvent.getFeeList()) {
                                                        addTcwF(tcwFinancesApiDataList, FinancialEventsType.IMAGINGSERVICESFEEEVENTLIST.getCode(),"FeeList",
                                                                feeComponent.getFeeType(), imagingServicesFeeEvent.getASIN(), 0, feeComponent.getFeeAmount().getCurrencyAmount(),
                                                                financialEventGroup.getFinancialEventGroupId(),
                                                                null, dateFormat.parse(imagingServicesFeeEvent.getPostedDate()),null,tcwFinancesEventGroups);
                                                    }
                                                }
                                            }
                                        }
                                        //NetworkComminglingTransactionEventList 网络混合交易事件列表
                                        if (financialEvents.getNetworkComminglingTransactionEventList() != null) {
                                            for (NetworkComminglingTransactionEvent networkComminglingTransactionEvent : financialEvents.getNetworkComminglingTransactionEventList()) {
                                                //TaxAmount
                                                addTcwF(tcwFinancesApiDataList, FinancialEventsType.NETWORKCOMMINGLINGTRANSACTIONEVENTLIST.getCode(), "TaxAmount",
                                                        networkComminglingTransactionEvent.getTransactionType(), networkComminglingTransactionEvent.getASIN(), 0,
                                                        networkComminglingTransactionEvent.getTaxAmount().getCurrencyAmount(),
                                                        financialEventGroup.getFinancialEventGroupId(), null,
                                                        dateFormat.parse(networkComminglingTransactionEvent.getPostedDate()),null,tcwFinancesEventGroups);
                                            }
                                        }
                                        //AffordabilityExpenseEventList 与负担能力促销相关的费用信息列表。
                                        if (financialEvents.getAffordabilityExpenseEventList() != null) {
                                            for (AffordabilityExpenseEvent affordabilityExpenseEvent : financialEvents.getAffordabilityExpenseEventList()) {
                                                addTcwF(tcwFinancesApiDataList, FinancialEventsType.AFFORDABILITYEXPENSEEVENTLIST.getCode(), "TotalExpense",
                                                        affordabilityExpenseEvent.getTransactionType(),
                                                        null, 0, affordabilityExpenseEvent.getTotalExpense().getCurrencyAmount(),
                                                        financialEventGroup.getFinancialEventGroupId(),  null,
                                                        dateFormat.parse(affordabilityExpenseEvent.getPostedDate()), String.valueOf(affordabilityExpenseEvent),tcwFinancesEventGroups);
                                            }
                                        }
                                        //AffordabilityExpenseReversalEventList 与负担能力促销相关的费用信息列表。
                                        if (financialEvents.getAffordabilityExpenseReversalEventList() != null) {
                                            for (AffordabilityExpenseEvent affordabilityExpenseEvent : financialEvents.getAffordabilityExpenseReversalEventList()) {
                                                addTcwF(tcwFinancesApiDataList, FinancialEventsType.AFFORDABILITYEXPENSEREVERSALEVENTLIST.getCode(), "TotalExpense",
                                                        affordabilityExpenseEvent.getTransactionType(),
                                                        null, 0, affordabilityExpenseEvent.getTotalExpense().getCurrencyAmount(),
                                                        financialEventGroup.getFinancialEventGroupId(), null,
                                                        dateFormat.parse(affordabilityExpenseEvent.getPostedDate()), String.valueOf(affordabilityExpenseEvent),tcwFinancesEventGroups);
                                            }
                                        }
                                        //RemovalShipmentEventList 移除发货事件信息列表
                                        if (financialEvents.getRemovalShipmentEventList() != null) {
                                            for (RemovalShipmentEvent removalShipmentEvent : financialEvents.getRemovalShipmentEventList()) {
                                                //总金额=Revenue + FeeAmount + TaxAmount + TaxWithheld
                                                for (RemovalShipmentItem removalShipmentItem : removalShipmentEvent.getRemovalShipmentItemList()) {
                                                    //revenue
                                                    addTcwF(tcwFinancesApiDataList, FinancialEventsType.REMOVALSHIPMENTEVENTLIST.getCode(), removalShipmentEvent.getTransactionType(),"revenue",
                                                            removalShipmentItem.getFulfillmentNetworkSKU(), removalShipmentItem.getQuantity(), removalShipmentItem.getRevenue().getCurrencyAmount(),
                                                            financialEventGroup.getFinancialEventGroupId(),
                                                            removalShipmentEvent.getOrderId(), dateFormat.parse(removalShipmentEvent.getPostedDate()), String.valueOf(removalShipmentItem),tcwFinancesEventGroups);
                                                    // taxAmount
                                                    addTcwF(tcwFinancesApiDataList, FinancialEventsType.REMOVALSHIPMENTEVENTLIST.getCode(), removalShipmentEvent.getTransactionType(),"taxAmount",
                                                            removalShipmentItem.getFulfillmentNetworkSKU(), removalShipmentItem.getQuantity(), removalShipmentItem.getTaxAmount().getCurrencyAmount(),
                                                            financialEventGroup.getFinancialEventGroupId(),
                                                            removalShipmentEvent.getOrderId(), dateFormat.parse(removalShipmentEvent.getPostedDate()), String.valueOf(removalShipmentItem),tcwFinancesEventGroups);
                                                    //feeAmount
                                                    addTcwF(tcwFinancesApiDataList, FinancialEventsType.REMOVALSHIPMENTEVENTLIST.getCode(), removalShipmentEvent.getTransactionType(),"feeAmount",
                                                            removalShipmentItem.getFulfillmentNetworkSKU(), removalShipmentItem.getQuantity(), removalShipmentItem.getFeeAmount().getCurrencyAmount(),
                                                            financialEventGroup.getFinancialEventGroupId(),
                                                            removalShipmentEvent.getOrderId(), dateFormat.parse(removalShipmentEvent.getPostedDate()), String.valueOf(removalShipmentItem),tcwFinancesEventGroups);
                                                    //taxWithheld
                                                    addTcwF(tcwFinancesApiDataList, FinancialEventsType.REMOVALSHIPMENTEVENTLIST.getCode(), removalShipmentEvent.getTransactionType(),"taxWithheld",
                                                            removalShipmentItem.getFulfillmentNetworkSKU(), removalShipmentItem.getQuantity(),removalShipmentItem.getTaxWithheld().getCurrencyAmount(),
                                                            financialEventGroup.getFinancialEventGroupId(),
                                                            removalShipmentEvent.getOrderId(), dateFormat.parse(removalShipmentEvent.getPostedDate()), String.valueOf(removalShipmentItem),tcwFinancesEventGroups);
                                                }
                                            }
                                        }
                                        //RemovalShipmentEventList 移除发货事件信息列表
                                        if (financialEvents.getRemovalShipmentAdjustmentEventList() != null) {
                                            for (RemovalShipmentAdjustmentEvent removalShipmentAdjustmentEvent : financialEvents.getRemovalShipmentAdjustmentEventList()) {
                                                Thread.sleep(1000L);
                                                //根据订单号取之前Liquidations的实际金额做计算
                                                ListFinancialEventsResponse listFinancialEventsResponse1 = api.listFinancialEventsByOrderId(removalShipmentAdjustmentEvent.getOrderId(), null, null);
                                                //总金额=Revenue + (原来的)FeeAmount + TaxAmount + TaxWithheld
                                                for (RemovalShipmentItemAdjustment removalShipmentItemAdjustment : removalShipmentAdjustmentEvent.getRemovalShipmentItemAdjustmentList()) {
                                                    //revenueAdjustment
                                                    addTcwF(tcwFinancesApiDataList, FinancialEventsType.REMOVALSHIPMENTADJUSTMENTEVENTLIST.getCode(), removalShipmentAdjustmentEvent.getTransactionType(),
                                                            "revenueAdjustment", removalShipmentItemAdjustment.getFulfillmentNetworkSKU(),
                                                            removalShipmentItemAdjustment.getAdjustedQuantity(), removalShipmentItemAdjustment.getRevenueAdjustment().getCurrencyAmount(),
                                                            financialEventGroup.getFinancialEventGroupId(), removalShipmentAdjustmentEvent.getOrderId(),
                                                            dateFormat.parse(removalShipmentAdjustmentEvent.getPostedDate()),null,tcwFinancesEventGroups);
                                                    //taxAmountAdjustment
                                                    addTcwF(tcwFinancesApiDataList, FinancialEventsType.REMOVALSHIPMENTADJUSTMENTEVENTLIST.getCode(), removalShipmentAdjustmentEvent.getTransactionType(),
                                                            "taxAmountAdjustment", removalShipmentItemAdjustment.getFulfillmentNetworkSKU(),
                                                            removalShipmentItemAdjustment.getAdjustedQuantity(), removalShipmentItemAdjustment.getTaxAmountAdjustment().getCurrencyAmount(),
                                                            financialEventGroup.getFinancialEventGroupId(), removalShipmentAdjustmentEvent.getOrderId(),
                                                            dateFormat.parse(removalShipmentAdjustmentEvent.getPostedDate()), null,tcwFinancesEventGroups);
                                                    //taxWithheldAdjustment
                                                    addTcwF(tcwFinancesApiDataList, FinancialEventsType.REMOVALSHIPMENTADJUSTMENTEVENTLIST.getCode(), removalShipmentAdjustmentEvent.getTransactionType(),
                                                            "taxWithheldAdjustment", removalShipmentItemAdjustment.getFulfillmentNetworkSKU(),
                                                            removalShipmentItemAdjustment.getAdjustedQuantity(), removalShipmentItemAdjustment.getTaxWithheldAdjustment().getCurrencyAmount(),
                                                            financialEventGroup.getFinancialEventGroupId(), removalShipmentAdjustmentEvent.getOrderId(),
                                                            dateFormat.parse(removalShipmentAdjustmentEvent.getPostedDate()), null,tcwFinancesEventGroups);
                                                    if (listFinancialEventsResponse1 != null) {
                                                        if (listFinancialEventsResponse1.getPayload() != null) {
                                                            if (listFinancialEventsResponse1.getPayload().getFinancialEvents() != null) {
                                                                for (RemovalShipmentEvent removalShipmentEvent : listFinancialEventsResponse1.getPayload().getFinancialEvents().getRemovalShipmentEventList()) {
                                                                    for (RemovalShipmentItem removalShipmentItem : removalShipmentEvent.getRemovalShipmentItemList()) {
                                                                        if (removalShipmentItem.getRemovalShipmentItemId().equals(removalShipmentItemAdjustment.getRemovalShipmentItemId())
                                                                                && removalShipmentItem.getFulfillmentNetworkSKU().equals(removalShipmentItemAdjustment.getFulfillmentNetworkSKU())
                                                                                && removalShipmentItem.getQuantity().equals(removalShipmentItemAdjustment.getAdjustedQuantity())
                                                                                && removalShipmentItem.getRevenue().getCurrencyAmount().equals(removalShipmentItemAdjustment.getRevenueAdjustment().getCurrencyAmount().negate())
                                                                                && removalShipmentItem.getTaxAmount().getCurrencyAmount().equals(removalShipmentItemAdjustment.getTaxAmountAdjustment().getCurrencyAmount().negate())
                                                                                && removalShipmentItem.getTaxWithheld().getCurrencyAmount().equals(removalShipmentItemAdjustment.getTaxWithheldAdjustment().getCurrencyAmount())
                                                                        ){
                                                                            //feeAmount
                                                                            addTcwF(tcwFinancesApiDataList, FinancialEventsType.REMOVALSHIPMENTADJUSTMENTEVENTLIST.getCode(), removalShipmentAdjustmentEvent.getTransactionType(),
                                                                                    "feeAmount", removalShipmentItemAdjustment.getFulfillmentNetworkSKU(),
                                                                                    removalShipmentItemAdjustment.getAdjustedQuantity(), removalShipmentItem.getFeeAmount().getCurrencyAmount().negate(),
                                                                                    financialEventGroup.getFinancialEventGroupId(), removalShipmentAdjustmentEvent.getOrderId(),
                                                                                    dateFormat.parse(removalShipmentAdjustmentEvent.getPostedDate()), null,tcwFinancesEventGroups);
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        //TrialShipmentEventList 有关试运财务事件的信息列表
                                        if (financialEvents.getTrialShipmentEventList() != null) {
                                            for (TrialShipmentEvent trialShipmentEvent : financialEvents.getTrialShipmentEventList()) {
                                                for (FeeComponent feeComponent : trialShipmentEvent.getFeeList()) {
                                                    addTcwF(tcwFinancesApiDataList, FinancialEventsType.TRIALSHIPMENTEVENTLIST.getCode(),"FeeList",
                                                            feeComponent.getFeeType(), trialShipmentEvent.getSKU(),
                                                            0, feeComponent.getFeeAmount().getCurrencyAmount(),
                                                            financialEventGroup.getFinancialEventGroupId(),
                                                            trialShipmentEvent.getAmazonOrderId(), dateFormat.parse(trialShipmentEvent.getPostedDate()),null,tcwFinancesEventGroups);
                                                }
                                            }
                                        }
                                        // TaxWithholdingEventList 	预扣税事件列表
                                        if (financialEvents.getTaxWithholdingEventList() != null) {
                                            for (TaxWithholdingEvent taxWithholdingEvent : financialEvents.getTaxWithholdingEventList()) {
                                                addTcwF(tcwFinancesApiDataList, FinancialEventsType.TAXWITHHOLDINGEVENTLIST.getCode(),"WithheldAmount",
                                                        FinancialEventsType.TAXWITHHOLDINGEVENTLIST.getCode(),
                                                        null, 0, taxWithholdingEvent.getWithheldAmount().getCurrencyAmount(),
                                                        financialEventGroup.getFinancialEventGroupId(),  null,
                                                        dateFormat.parse(taxWithholdingEvent.getPostedDate()),null,tcwFinancesEventGroups);
                                            }
                                        }
                                        //TDSReimbursementEventList TDS报销事件列表
                                        if (financialEvents.getTdSReimbursementEventList() != null) {
                                            for (TDSReimbursementEvent tdsReimbursementEvent : financialEvents.getTdSReimbursementEventList()) {
                                                addTcwF(tcwFinancesApiDataList, FinancialEventsType.TDSREIMBURSEMENTEVENTLIST.getCode(),FinancialEventsType.TDSREIMBURSEMENTEVENTLIST.getCode(),
                                                        FinancialEventsType.TDSREIMBURSEMENTEVENTLIST.getCode(),
                                                        null, 0, tdsReimbursementEvent.getReimbursedAmount().getCurrencyAmount(),
                                                        financialEventGroup.getFinancialEventGroupId(),  tdsReimbursementEvent.getTdSOrderId(),
                                                        dateFormat.parse(tdsReimbursementEvent.getPostedDate()),null,tcwFinancesEventGroups);
                                            }
                                        }
                                        //AdhocDisbursementEventList 临时支付事件列表
                                        if (financialEvents.getAdhocDisbursementEventList() != null) {
                                            for (AdhocDisbursementEvent adhocDisbursementEvent : financialEvents.getAdhocDisbursementEventList()) {
                                                addTcwF(tcwFinancesApiDataList, FinancialEventsType.ADHOCDISBURSEMENTEVENTLIST.getCode(),FinancialEventsType.ADHOCDISBURSEMENTEVENTLIST.getCode(),
                                                        adhocDisbursementEvent.getTransactionType(),
                                                        null, 0, adhocDisbursementEvent.getTransactionAmount().getCurrencyAmount(),
                                                        financialEventGroup.getFinancialEventGroupId(),  null,
                                                        dateFormat.parse(adhocDisbursementEvent.getPostedDate()),null,tcwFinancesEventGroups);
                                            }
                                        }
                                        //ChargeRefundEventList 充值退款活动列表
                                        if (financialEvents.getChargeRefundEventList() != null) {
                                            for (ChargeRefundEvent chargeRefundEvent : financialEvents.getChargeRefundEventList()) {
                                                if (chargeRefundEvent.getChargeRefundTransactions() != null) {
                                                    for (ChargeRefundTransaction chargeRefundTransaction : chargeRefundEvent.getChargeRefundTransactions()){
                                                        addTcwF(tcwFinancesApiDataList, FinancialEventsType.CHARGEREFUNDEVENTLIST.getCode(),FinancialEventsType.CHARGEREFUNDEVENTLIST.getCode(),
                                                                chargeRefundTransaction.getChargeType(), null, 0, chargeRefundTransaction.getChargeAmount().getCurrencyAmount(),
                                                                financialEventGroup.getFinancialEventGroupId(),  null,
                                                                dateFormat.parse(chargeRefundEvent.getPostedDate()),null,tcwFinancesEventGroups);
                                                    }
                                                }
                                            }
                                        }
                                        //FailedAdhocDisbursementEventList 失败的临时支付事件列表
                                        if (financialEvents.getFailedAdhocDisbursementEventList() != null) {
                                            for (FailedAdhocDisbursementEvent failedAdhocDisbursementEvent : financialEvents.getFailedAdhocDisbursementEventList()) {
                                                addTcwF(tcwFinancesApiDataList, FinancialEventsType.FAILEDADHOCDISBURSEMENTEVENTLIST.getCode(),FinancialEventsType.FAILEDADHOCDISBURSEMENTEVENTLIST.getCode(),
                                                        failedAdhocDisbursementEvent.getFundsTransfersType(), null, 0, failedAdhocDisbursementEvent.getTransferAmount().getCurrencyAmount(),
                                                        financialEventGroup.getFinancialEventGroupId(),  null,
                                                        dateFormat.parse(failedAdhocDisbursementEvent.getPostedDate()),null,tcwFinancesEventGroups);
                                            }
                                        }
                                        //ValueAddedServiceChargeEventList 与增值服务费相关的事件。。
                                        if (financialEvents.getValueAddedServiceChargeEventList() != null) {
                                            for (ValueAddedServiceChargeEvent valueAddedServiceChargeEvent : financialEvents.getValueAddedServiceChargeEventList()) {
                                                addTcwF(tcwFinancesApiDataList, FinancialEventsType.VALUEADDEDSERVICECHARGEEVENTLIST.getCode(),FinancialEventsType.VALUEADDEDSERVICECHARGEEVENTLIST.getCode(),
                                                        valueAddedServiceChargeEvent.getTransactionType(), null, 0, valueAddedServiceChargeEvent.getTransactionAmount().getCurrencyAmount(),
                                                        financialEventGroup.getFinancialEventGroupId(),  null,
                                                        dateFormat.parse(valueAddedServiceChargeEvent.getPostedDate()),null,tcwFinancesEventGroups);
                                            }
                                        }
                                        //CapacityReservationBillingEventList 容量预留计费事件列表。。
                                        if (financialEvents.getCapacityReservationBillingEventList() != null) {
                                            for (CapacityReservationBillingEvent capacityReservationBillingEvent : financialEvents.getCapacityReservationBillingEventList()) {
                                                addTcwF(tcwFinancesApiDataList, FinancialEventsType.CAPACITYRESERVATIONBILLINGEVENTLIST.getCode(),FinancialEventsType.CAPACITYRESERVATIONBILLINGEVENTLIST.getCode(),
                                                        capacityReservationBillingEvent.getTransactionType(), null, 0, capacityReservationBillingEvent.getTransactionAmount().getCurrencyAmount(),
                                                        financialEventGroup.getFinancialEventGroupId(),  null,
                                                        dateFormat.parse(capacityReservationBillingEvent.getPostedDate()),null,tcwFinancesEventGroups);
                                            }
                                        }
                                    }

                                    //根据MarketplaceName 设置网店信息
                                    if (tcwFinancesEventGroups.getMarketplaceName() != null) {
                                        TpAmazonShop tpAmazonShop = new TpAmazonShop()
                                                .addLeftJoin("TB_Site ts on ts.id = A.SiteId")//站点
                                                .setSellerId(jsonObject.get("sellerId").toString())
                                                .where("ts.AmazonSalesChannel = '" + tcwFinancesEventGroups.getMarketplaceName() + "'")
                                                .queryFirst();
                                        if (tpAmazonShop != null) {
                                            tcwFinancesEventGroups.setShopGuid(tpAmazonShop.getGuid());
                                            tcwFinancesEventGroups.setShopId(String.valueOf(tpAmazonShop.getId()));
                                            tcwFinancesEventGroups.setShopNameMc(tpAmazonShop.getShopName());
                                        }
                                    }
                                    tcwFinancesEventGroupsList.add(tcwFinancesEventGroups);
                                }
                            }
                        }
                    }
                    if (listFinancialEventGroupsPayload.getNextToken() != null){
                        nextToken = listFinancialEventGroupsPayload.getNextToken();
                    }else {
                        isTrue = false;
                    }
                }else {
                    isTrue = false;
                }
                int insertLength = tcwFinancesApiDataList.size();
                int i = 0;
                while (insertLength > 20) {
                    diySqlMapper.insertBatchTcwFinancesApiData(tcwFinancesApiDataList.subList(i, i + 20));
                    i = i + 20;
                    insertLength = insertLength - 20;
                }
                if (insertLength > 0) {
                    diySqlMapper.insertBatchTcwFinancesApiData(tcwFinancesApiDataList.subList(i, i + insertLength));
                }
                int financesEventGroupsLength = tcwFinancesEventGroupsList.size();
                int j = 0;
                while (financesEventGroupsLength > 50) {
                    diySqlMapper.updateBatchFinancesEventGroups(tcwFinancesEventGroupsList.subList(j, j + 50));
                    j = j + 50;
                    financesEventGroupsLength = financesEventGroupsLength - 50;
                }
                if (financesEventGroupsLength > 0) {
                    diySqlMapper.updateBatchFinancesEventGroups(tcwFinancesEventGroupsList.subList(j, j + financesEventGroupsLength));
                }
            }
        }catch (Exception ex){
            apiResponse.setCode(500);
            apiResponse.setMessage("ECP_API定时获取亚马逊财务事件信息出错，具体错误信息为："+ex.getMessage());
        }
        apiResponse.setCode(0);
        apiResponse.setMessage("成功!");
        return apiResponse;
    }

    @Override
    public ApiResponse getFinancesInfo(TpAmazonSeller tpAmazonSeller, String startTimeStr, String endTimeStr) {
        ApiResponse apiResponse = new ApiResponse();
        List<TcwFinancesApiInFo> orderList = null;
        List<TcwFinancesApiInFo> orderListNew = null;
        //订单id和订单事件分组数据
        List<TcwFinancesApiInFoId> orderIdList = null;
        List<TcwFinancesApiInFoId> orderIdListNew = null;
        TcwFinancesApiInFo tcwFinancesApiInFo = null;
        TcwFinancesApiInFoId tcwFinancesApiInFoId = null;
        List<TcwFinancesEventGroups> tcwFinancesEventGroupsList = null;
        try {
//            查询分组事件
            tcwFinancesEventGroupsList = new TcwFinancesEventGroups()
                    .where("A.CompanyID = '" + tpAmazonSeller.getVgsbm() +"'" +
                            "AND A.EndDate BETWEEN '" + startTimeStr + "' AND  '" + endTimeStr + "'"
                            + "AND A.RegionCode = '" + tpAmazonSeller.getRegionCode() + "'")
                    .queryList();

            for (TcwFinancesEventGroups tcwFinancesEventGroups : tcwFinancesEventGroupsList){
                diySqlMapper.deleteFinancesApiInFo(tcwFinancesEventGroups.getFinancialEventGroupId());
                diySqlMapper.deleteFinancesApiInFoId(tcwFinancesEventGroups.getFinancialEventGroupId());

                tcwFinancesEventGroups.setTwoCurrencyAmount(BigDecimal.ZERO);
                orderList = new ArrayList<>();
                orderIdList = new ArrayList<>();
                //查出对应的api数据
                List<TcwFinancesApiData> tcwFinancesApiDataList = new TcwFinancesApiData()
                        .where("A.FinancialEventGroupId = '" + tcwFinancesEventGroups.getFinancialEventGroupId()+"'").queryList();
                //查出对应商品sku信息
                List<Map<String, Object>> tpAmazonShopProductList = new ArrayList<>();
                if (tcwFinancesEventGroups.getShopId() != null){
                    tpAmazonShopProductList = new TpAmazonShopProduct()
                            .addLeftJoin("TP_ProductBasis t2 on A.code = t2.code")
                            .addField("t2.name as name")
                            .where("A.ShopId = '" + tcwFinancesEventGroups.getShopId()+"' AND A.Asin IS NOT NULL")
                            .queryMap();
                }

                for (TcwFinancesApiData tcwFinancesApiData : tcwFinancesApiDataList){
                    //Transfer
                    addFinancesApiInFo(orderList,FinancialEventsType.TRANSFER.getCode(),tcwFinancesApiData.getType(),tcwFinancesApiData,tcwFinancesEventGroups,tpAmazonShopProductList,orderIdList);
                    //期初欠费金额
                    addFinancesApiInFo(orderList,FinancialEventsType.BEGINNINGBALANCE.getCode(),tcwFinancesApiData.getType(),tcwFinancesApiData,tcwFinancesEventGroups,tpAmazonShopProductList,orderIdList);
                    //ShipmentEventList 订单事件 | 装运结算事件列表 |退款事件列表 | 保证索赔事件列表
                    addOrder(FinancialEventsType.SHIPMENTEVENTLIST.getCode(),tcwFinancesApiData.getType(), tcwFinancesApiData,orderList,"Order",tcwFinancesEventGroups,tpAmazonShopProductList,orderIdList);
                    addOrder(FinancialEventsType.SHIPMENTSETTLEEVENTLIST.getCode(),tcwFinancesApiData.getType(), tcwFinancesApiData,orderList,"Order",tcwFinancesEventGroups,tpAmazonShopProductList,orderIdList);
                    addOrder(FinancialEventsType.REFUNDEVENTLIST.getCode(),tcwFinancesApiData.getType(), tcwFinancesApiData,orderList,"Refund",tcwFinancesEventGroups,tpAmazonShopProductList,orderIdList);
                    addOrder(FinancialEventsType.GUARANTEECLAIMEVENTLIST.getCode(),tcwFinancesApiData.getType(), tcwFinancesApiData,orderList,"Refund",tcwFinancesEventGroups,tpAmazonShopProductList,orderIdList);
                    addOrder(FinancialEventsType.CHARGEBACKEVENTLIST.getCode(),tcwFinancesApiData.getType(), tcwFinancesApiData,orderList,"Refund",tcwFinancesEventGroups,tpAmazonShopProductList,orderIdList);

                    //与卖家的 Pay with Amazon 账户相关的事件列表
                    addFinancesApiInFo(orderList,FinancialEventsType.PAYWITHAMAZONEVENTLIST.getCode(),tcwFinancesApiData.getType(),tcwFinancesApiData,tcwFinancesEventGroups,tpAmazonShopProductList,orderIdList);
                    //有关解决方案提供商信用的信息列表。
                    addFinancesApiInFo(orderList,FinancialEventsType.SERVICEPROVIDERCREDITEVENTLIST.getCode(),tcwFinancesApiData.getType(),tcwFinancesApiData,tcwFinancesEventGroups,tpAmazonShopProductList,orderIdList);
                    //有关 Retrocharge 或 RetrochargeReversal 事件的信息列表。
                    if (FinancialEventsType.RETROCHARGEEVENTLIST.getCode().equals(tcwFinancesApiData.getType())){
                        orderListNew = orderList.stream().filter(tcwFinancesApiInFoNew ->
                                FinancialEventsType.RETROCHARGEEVENTLIST.getCode().equals(tcwFinancesApiInFoNew.getType())
                                        && tcwFinancesApiData.getFinancialEventGroupId().equals(tcwFinancesApiInFoNew.getFinancialEventGroupId()))
                                .collect(Collectors.toList());
                        if (orderListNew.size() == 0){
                            tcwFinancesApiInFo = new TcwFinancesApiInFo();
                            setInFo(tcwFinancesApiInFo,tcwFinancesEventGroups);
                            tcwFinancesApiInFo.setType(tcwFinancesApiData.getType());
                            tcwFinancesApiInFo.setSku(tcwFinancesApiData.getSku());
                            tcwFinancesApiInFo.setFinancialEventGroupId(tcwFinancesApiData.getFinancialEventGroupId());
                            tcwFinancesApiInFo.setGroupId(tcwFinancesApiData.getGroupId());
                            tcwFinancesApiInFo.setPurchaseDate(tcwFinancesApiData.getPurchaseDate());
                            tcwFinancesApiInFo.setDataType(tcwFinancesApiData.getDataType());
                            tcwFinancesApiInFo.setThereDataType(tcwFinancesApiData.getThereDataType());
                            //设置商品名称
                            getProductCode(tcwFinancesApiData,tpAmazonShopProductList, tcwFinancesEventGroups,tcwFinancesApiInFo);
                        }else {
                            tcwFinancesApiInFo = orderListNew.get(0);
                        }
                        //总金额
                        tcwFinancesApiInFo.setTotal(tcwFinancesApiInFo.getTotal().add(tcwFinancesApiData.getTotal()));

                        if (orderListNew.size() == 0){
                            orderList.add(tcwFinancesApiInFo);
                        }

                        orderIdListNew = orderIdList.stream().filter(tcwFinancesApiInFoNew ->
                                FinancialEventsType.RETROCHARGEEVENTLIST.getCode().equals(tcwFinancesApiInFoNew.getType())
                                        && tcwFinancesApiData.getFinancialEventGroupId().equals(tcwFinancesApiInFoNew.getFinancialEventGroupId()))
                                .collect(Collectors.toList());
                        if (orderIdListNew.size() == 0){
                            tcwFinancesApiInFoId = new TcwFinancesApiInFoId();
                            setInFoId(tcwFinancesApiInFoId,tcwFinancesEventGroups);
                            tcwFinancesApiInFoId.setType(tcwFinancesApiData.getType());
                            tcwFinancesApiInFoId.setSku(tcwFinancesApiData.getSku());
                            tcwFinancesApiInFoId.setFinancialEventGroupId(tcwFinancesApiData.getFinancialEventGroupId());
                            tcwFinancesApiInFoId.setGroupId(tcwFinancesApiData.getGroupId());
                            tcwFinancesApiInFoId.setPurchaseDate(tcwFinancesApiData.getPurchaseDate());
                            tcwFinancesApiInFoId.setDataType(tcwFinancesApiData.getDataType());
                            tcwFinancesApiInFoId.setThereDataType(tcwFinancesApiData.getThereDataType());
                            tcwFinancesApiInFoId.setAmazonOrderId(tcwFinancesApiData.getAmazonOrderId());
                            //设置商品名称
                            getProductCodeId(tcwFinancesApiData,tpAmazonShopProductList, tcwFinancesEventGroups,tcwFinancesApiInFoId);
                        }else {
                            tcwFinancesApiInFoId = orderIdListNew.get(0);
                        }
                        tcwFinancesApiInFoId.setTotal(tcwFinancesApiInFoId.getTotal().add(tcwFinancesApiData.getTotal()));

                        if (orderIdListNew.size() == 0){
                            orderIdList.add(tcwFinancesApiInFoId);
                        }
                        if (!FinancialEventsType.TRANSFER.getCode().equals(tcwFinancesApiData.getType())){
                            //二次金额相加
                            tcwFinancesEventGroups.setTwoCurrencyAmount(tcwFinancesEventGroups.getTwoCurrencyAmount().add(tcwFinancesApiData.getTotal()));
                        }
                    }
                    //RentalTransactionEventList 租赁交易事件信息列表
                    addFinancesApiInFo(orderList,FinancialEventsType.RENTALTRANSACTIONEVENTLIST.getCode(),tcwFinancesApiData.getType(),tcwFinancesApiData,tcwFinancesEventGroups,tpAmazonShopProductList,orderIdList);;
                    //ProductAdsPaymentEventList  赞助产品付款活动列表
                    addFinancesApiInFo(orderList,FinancialEventsType.PRODUCTADSPAYMENTEVENTLIST.getCode(),tcwFinancesApiData.getType(),tcwFinancesApiData,tcwFinancesEventGroups,tpAmazonShopProductList,orderIdList);
                    //ServiceFeeEventList 有关服务费事件的信息列表
                     if (FinancialEventsType.SERVICEFEEEVENTLIST.getCode().equals(tcwFinancesApiData.getType())){
                        orderListNew = orderList.stream().filter(tcwFinancesApiInFoNew ->
                            FinancialEventsType.SERVICEFEEEVENTLIST.getCode().equals(tcwFinancesApiInFoNew.getType())
                                    && tcwFinancesApiData.getFinancialEventGroupId().equals(tcwFinancesApiInFoNew.getFinancialEventGroupId()))
                                 .collect(Collectors.toList());
                        if (orderListNew.size() == 0) {
                            tcwFinancesApiInFo = new TcwFinancesApiInFo();
                            setInFo(tcwFinancesApiInFo,tcwFinancesEventGroups);
                            tcwFinancesApiInFo.setType(tcwFinancesApiData.getType());
                            tcwFinancesApiInFo.setSku(tcwFinancesApiData.getSku());
                            tcwFinancesApiInFo.setFinancialEventGroupId(tcwFinancesApiData.getFinancialEventGroupId());
                            tcwFinancesApiInFo.setGroupId(tcwFinancesApiData.getGroupId());
                            tcwFinancesApiInFo.setPurchaseDate(tcwFinancesApiData.getPurchaseDate());
                            tcwFinancesApiInFo.setDataType(tcwFinancesApiData.getDataType());
                            tcwFinancesApiInFo.setThereDataType("FBA Inventory Fee");
                            //设置商品名称
                            getProductCode(tcwFinancesApiData,tpAmazonShopProductList, tcwFinancesEventGroups,tcwFinancesApiInFo);
                        } else {
                            tcwFinancesApiInFo = orderListNew.get(0);
                        }
                        //总金额
                        tcwFinancesApiInFo.setTotal(tcwFinancesApiInFo.getTotal().add(tcwFinancesApiData.getTotal()));

                        if (orderListNew.size() == 0){
                            orderList.add(tcwFinancesApiInFo);
                        }

                         orderIdListNew = orderIdList.stream().filter(tcwFinancesApiInFoNew ->
                                 FinancialEventsType.SERVICEFEEEVENTLIST.getCode().equals(tcwFinancesApiInFoNew.getType())
                                         && tcwFinancesApiData.getFinancialEventGroupId().equals(tcwFinancesApiInFoNew.getFinancialEventGroupId()))
                                 .collect(Collectors.toList());
                         if (orderIdListNew.size() == 0){
                             tcwFinancesApiInFoId = new TcwFinancesApiInFoId();
                             setInFoId(tcwFinancesApiInFoId,tcwFinancesEventGroups);
                             tcwFinancesApiInFoId.setType(tcwFinancesApiData.getType());
                             tcwFinancesApiInFoId.setSku(tcwFinancesApiData.getSku());
                             tcwFinancesApiInFoId.setFinancialEventGroupId(tcwFinancesApiData.getFinancialEventGroupId());
                             tcwFinancesApiInFoId.setGroupId(tcwFinancesApiData.getGroupId());
                             tcwFinancesApiInFoId.setPurchaseDate(tcwFinancesApiData.getPurchaseDate());
                             tcwFinancesApiInFoId.setDataType(tcwFinancesApiData.getDataType());
                             tcwFinancesApiInFoId.setThereDataType(tcwFinancesApiData.getThereDataType());
                             tcwFinancesApiInFoId.setAmazonOrderId(tcwFinancesApiData.getAmazonOrderId());
                             //设置商品名称
                             getProductCodeId(tcwFinancesApiData,tpAmazonShopProductList, tcwFinancesEventGroups,tcwFinancesApiInFoId);
                         }else {
                             tcwFinancesApiInFoId = orderIdListNew.get(0);
                         }
                         tcwFinancesApiInFoId.setTotal(tcwFinancesApiInFoId.getTotal().add(tcwFinancesApiData.getTotal()));

                         if (orderIdListNew.size() == 0){
                             orderIdList.add(tcwFinancesApiInFoId);
                         }

                        if (!FinancialEventsType.TRANSFER.getCode().equals(tcwFinancesApiData.getType())){
                            //二次金额
                            tcwFinancesEventGroups.setTwoCurrencyAmount(tcwFinancesEventGroups.getTwoCurrencyAmount().add(tcwFinancesApiData.getTotal()));
                        }
                     }
                    //SellerDealPaymentEventList 交易相关费用的支付事件列表
                    addFinancesApiInFo(orderList,FinancialEventsType.SELLERDEALPAYMENTEVENTLIST.getCode(),tcwFinancesApiData.getType(),tcwFinancesApiData,tcwFinancesEventGroups,tpAmazonShopProductList,orderIdList);
                    //类型为at的数据通过DebtRecoveryEventList中的recoveryAmount数据获取
                    addFinancesApiInFo(orderList,FinancialEventsType.DEBTRECOVERYEVENTLIST.getCode(),tcwFinancesApiData.getType(),tcwFinancesApiData,tcwFinancesEventGroups,tpAmazonShopProductList,orderIdList);
                    //LoanServicingEventList 贷款服务事件列表
                    addFinancesApiInFo(orderList,FinancialEventsType.LOANSERVICINGEVENTLIST.getCode(),tcwFinancesApiData.getType(),tcwFinancesApiData,tcwFinancesEventGroups,tpAmazonShopProductList,orderIdList);
                    //AdjustmentEventList 卖家账户的调整事件信息列表
                    if (FinancialEventsType.ADJUSTMENTEVENTLIST.getCode().equals(tcwFinancesApiData.getType())) {
                        String sku = tcwFinancesApiData.getSku() == null ? "" :tcwFinancesApiData.getSku();
                        if (FinancialEventsType.ADJUSTMENTITEMLIST.getCode().equals(tcwFinancesApiData.getDataType())){
                            orderListNew = orderList.stream().filter(tcwFinancesApiInFoNew -> FinancialEventsType.ADJUSTMENTEVENTLIST.getCode().equals(tcwFinancesApiInFoNew.getType())
                                    && FinancialEventsType.ADJUSTMENTITEMLIST.getCode().equals(tcwFinancesApiInFoNew.getDataType())
                                    && sku.equals(tcwFinancesApiInFoNew.getSku())
                                    && tcwFinancesApiData.getFinancialEventGroupId().equals(tcwFinancesApiInFoNew.getFinancialEventGroupId()))
                                    .collect(Collectors.toList());
                            if (orderListNew.size() == 0) {
                                tcwFinancesApiInFo = new TcwFinancesApiInFo();
                                setInFo(tcwFinancesApiInFo,tcwFinancesEventGroups);
                                tcwFinancesApiInFo.setType(tcwFinancesApiData.getType());
                                tcwFinancesApiInFo.setSku(tcwFinancesApiData.getSku());
                                tcwFinancesApiInFo.setFinancialEventGroupId(tcwFinancesApiData.getFinancialEventGroupId());
                                tcwFinancesApiInFo.setGroupId(tcwFinancesApiData.getGroupId());
                                tcwFinancesApiInFo.setPurchaseDate(tcwFinancesApiData.getPurchaseDate());
                                tcwFinancesApiInFo.setDataType(tcwFinancesApiData.getDataType());
                                tcwFinancesApiInFo.setThereDataType(tcwFinancesApiData.getThereDataType());
                                //设置商品名称
                                getProductCode(tcwFinancesApiData,tpAmazonShopProductList, tcwFinancesEventGroups,tcwFinancesApiInFo);
                            }else {
                                tcwFinancesApiInFo = orderListNew.get(0);
                            }
                            //Quantity 数量
                            tcwFinancesApiInFo.setQuantity(tcwFinancesApiInFo.getQuantity() + tcwFinancesApiData.getQuantity());

                            tcwFinancesApiInFo.setTotal(tcwFinancesApiInFo.getTotal().add(tcwFinancesApiData.getTotal()));
                            if (orderListNew.size() == 0){
                                orderList.add(tcwFinancesApiInFo);
                            }

                            orderIdListNew = orderIdList.stream().filter(tcwFinancesApiInFoNew -> FinancialEventsType.ADJUSTMENTEVENTLIST.getCode().equals(tcwFinancesApiInFoNew.getType())
                                    && FinancialEventsType.ADJUSTMENTITEMLIST.getCode().equals(tcwFinancesApiInFoNew.getDataType())
                                    && sku.equals(tcwFinancesApiInFoNew.getSku())
                                    && tcwFinancesApiData.getFinancialEventGroupId().equals(tcwFinancesApiInFoNew.getFinancialEventGroupId()))
                                    .collect(Collectors.toList());
                            if (orderIdListNew.size() == 0){
                                tcwFinancesApiInFoId = new TcwFinancesApiInFoId();
                                setInFoId(tcwFinancesApiInFoId,tcwFinancesEventGroups);
                                tcwFinancesApiInFoId.setType(tcwFinancesApiData.getType());
                                tcwFinancesApiInFoId.setSku(tcwFinancesApiData.getSku());
                                tcwFinancesApiInFoId.setFinancialEventGroupId(tcwFinancesApiData.getFinancialEventGroupId());
                                tcwFinancesApiInFoId.setGroupId(tcwFinancesApiData.getGroupId());
                                tcwFinancesApiInFoId.setPurchaseDate(tcwFinancesApiData.getPurchaseDate());
                                tcwFinancesApiInFoId.setDataType(tcwFinancesApiData.getDataType());
                                tcwFinancesApiInFoId.setThereDataType(tcwFinancesApiData.getThereDataType());
                                tcwFinancesApiInFoId.setAmazonOrderId(tcwFinancesApiData.getAmazonOrderId());
                                //设置商品名称
                                getProductCodeId(tcwFinancesApiData,tpAmazonShopProductList, tcwFinancesEventGroups,tcwFinancesApiInFoId);
                            }else {
                                tcwFinancesApiInFoId = orderIdListNew.get(0);
                            }
                            tcwFinancesApiInFoId.setTotal(tcwFinancesApiInFoId.getTotal().add(tcwFinancesApiData.getTotal()));

                            if (orderIdListNew.size() == 0){
                                orderIdList.add(tcwFinancesApiInFoId);
                            }


                            if (!FinancialEventsType.TRANSFER.getCode().equals(tcwFinancesApiData.getType())){
                                //二次金额相加
                                tcwFinancesEventGroups.setTwoCurrencyAmount(tcwFinancesEventGroups.getTwoCurrencyAmount().add(tcwFinancesApiData.getTotal()));
                            }
                        }else {
                            addFinancesApiInFo(orderList,FinancialEventsType.ADJUSTMENTEVENTLIST.getCode(),tcwFinancesApiData.getType(),tcwFinancesApiData,tcwFinancesEventGroups,tpAmazonShopProductList,orderIdList);
                        }
                    }
                    //SAFETReimbursementEventList SAFET 报销事件列表
                    addFinancesApiInFo(orderList,FinancialEventsType.SAFETREIMBURSEMENTEVENTLIST.getCode(),tcwFinancesApiData.getType(),tcwFinancesApiData,tcwFinancesEventGroups,tpAmazonShopProductList,orderIdList);
                    //SellerReviewEnrollmentPaymentEventList 有关早期审稿人计划费用事件的信息列表。
                    addFinancesApiInFo(orderList,FinancialEventsType.SELLERREVIEWENROLLMENTPAYMENTEVENTLIST.getCode(),tcwFinancesApiData.getType(),tcwFinancesApiData,tcwFinancesEventGroups,tpAmazonShopProductList,orderIdList);
                    //FBALiquidationEventList FBA库存清算付款事件列表
                    addFinancesApiInFo(orderList,FinancialEventsType.FBALIQUIDATIONEVENTLIST.getCode(),tcwFinancesApiData.getType(),tcwFinancesApiData,tcwFinancesEventGroups,tpAmazonShopProductList,orderIdList);
                    //CouponPaymentEventList  优惠券支付事件信息列表
                    addFinancesApiInFo(orderList,FinancialEventsType.COUPONPAYMENTEVENTLIST.getCode(),tcwFinancesApiData.getType(),tcwFinancesApiData,tcwFinancesEventGroups,tpAmazonShopProductList,orderIdList);
                    //ImagingServicesFeeEventList 与 Amazon Imaging 服务相关的费用事件列表。
                    addFinancesApiInFo(orderList,FinancialEventsType.IMAGINGSERVICESFEEEVENTLIST.getCode(),tcwFinancesApiData.getType(),tcwFinancesApiData,tcwFinancesEventGroups,tpAmazonShopProductList,orderIdList);
                    //NetworkComminglingTransactionEventList 网络混合交易事件列表
                    addFinancesApiInFo(orderList,FinancialEventsType.NETWORKCOMMINGLINGTRANSACTIONEVENTLIST.getCode(),tcwFinancesApiData.getType(),tcwFinancesApiData,tcwFinancesEventGroups,tpAmazonShopProductList,orderIdList);
                    //AffordabilityExpenseEventList 与负担能力促销相关的费用信息列表。
                    addFinancesApiInFo(orderList,FinancialEventsType.AFFORDABILITYEXPENSEEVENTLIST.getCode(),tcwFinancesApiData.getType(),tcwFinancesApiData,tcwFinancesEventGroups,tpAmazonShopProductList,orderIdList);
                    //AffordabilityExpenseReversalEventList 与负担能力促销相关的费用信息列表。
                    addFinancesApiInFo(orderList,FinancialEventsType.AFFORDABILITYEXPENSEREVERSALEVENTLIST.getCode(),tcwFinancesApiData.getType(),tcwFinancesApiData,tcwFinancesEventGroups,tpAmazonShopProductList,orderIdList);
                    //RemovalShipmentEventList 移除发货事件信息列表
                    if (FinancialEventsType.REMOVALSHIPMENTEVENTLIST.getCode().equals(tcwFinancesApiData.getType())) {
                        orderListNew = orderList.stream().filter(tcwFinancesApiInFoNew -> FinancialEventsType.REMOVALSHIPMENTEVENTLIST.getCode().equals(tcwFinancesApiInFoNew.getType())
                                && tcwFinancesApiData.getSku().equals(tcwFinancesApiInFoNew.getSku())
                                && tcwFinancesApiData.getFinancialEventGroupId().equals(tcwFinancesApiInFoNew.getFinancialEventGroupId()))
                                .collect(Collectors.toList());
                        if (orderListNew.size() == 0) {
                            tcwFinancesApiInFo = new TcwFinancesApiInFo();
                            setInFo(tcwFinancesApiInFo,tcwFinancesEventGroups);
                            tcwFinancesApiInFo.setType(tcwFinancesApiData.getType());
                            tcwFinancesApiInFo.setSku(tcwFinancesApiData.getSku());
                            tcwFinancesApiInFo.setFinancialEventGroupId(tcwFinancesApiData.getFinancialEventGroupId());
                            tcwFinancesApiInFo.setGroupId(tcwFinancesApiData.getGroupId());
                            tcwFinancesApiInFo.setPurchaseDate(tcwFinancesApiData.getPurchaseDate());
                            tcwFinancesApiInFo.setDataType(tcwFinancesApiData.getDataType());
                            tcwFinancesApiInFo.setThereDataType("Liquidations");
                            //设置商品名称
                            getProductCode(tcwFinancesApiData,tpAmazonShopProductList, tcwFinancesEventGroups,tcwFinancesApiInFo);
                        }else {
                            tcwFinancesApiInFo = orderListNew.get(0);
                        }

                        orderIdListNew = orderIdList.stream().filter(tcwFinancesApiInFoNew -> FinancialEventsType.REMOVALSHIPMENTEVENTLIST.getCode().equals(tcwFinancesApiInFoNew.getType())
                                && tcwFinancesApiData.getSku().equals(tcwFinancesApiInFoNew.getSku())
                                && tcwFinancesApiData.getFinancialEventGroupId().equals(tcwFinancesApiInFoNew.getFinancialEventGroupId()))
                                .collect(Collectors.toList());
                        if (orderIdListNew.size() == 0){
                            tcwFinancesApiInFoId = new TcwFinancesApiInFoId();
                            setInFoId(tcwFinancesApiInFoId,tcwFinancesEventGroups);
                            tcwFinancesApiInFoId.setType(tcwFinancesApiData.getType());
                            tcwFinancesApiInFoId.setSku(tcwFinancesApiData.getSku());
                            tcwFinancesApiInFoId.setFinancialEventGroupId(tcwFinancesApiData.getFinancialEventGroupId());
                            tcwFinancesApiInFoId.setGroupId(tcwFinancesApiData.getGroupId());
                            tcwFinancesApiInFoId.setPurchaseDate(tcwFinancesApiData.getPurchaseDate());
                            tcwFinancesApiInFoId.setDataType(tcwFinancesApiData.getDataType());
                            tcwFinancesApiInFoId.setThereDataType(tcwFinancesApiData.getThereDataType());
                            tcwFinancesApiInFoId.setAmazonOrderId(tcwFinancesApiData.getAmazonOrderId());
                            //设置商品名称
                            getProductCodeId(tcwFinancesApiData,tpAmazonShopProductList, tcwFinancesEventGroups,tcwFinancesApiInFoId);
                        }else {
                            tcwFinancesApiInFoId = orderIdListNew.get(0);
                        }

                        //revenue
                        if (FinancialEventsType.WHOLESALE_LIQUIDATION.getCode().equals(tcwFinancesApiData.getDataType())
                                && FinancialEventsType.REVENUE.getCode().equals(tcwFinancesApiData.getThereDataType())){
                            //总数量
                            tcwFinancesApiInFo.setQuantity(tcwFinancesApiInFo.getQuantity() + tcwFinancesApiData.getQuantity());
                            tcwFinancesApiInFoId.setQuantity(tcwFinancesApiInFoId.getQuantity() + tcwFinancesApiData.getQuantity());
                        }

                        //总金额
                        tcwFinancesApiInFo.setTotal(tcwFinancesApiInFo.getTotal().add(tcwFinancesApiData.getTotal()));
                        tcwFinancesApiInFoId.setTotal(tcwFinancesApiInFoId.getTotal().add(tcwFinancesApiData.getTotal()));
                        if (orderListNew.size() == 0){
                            orderList.add(tcwFinancesApiInFo);
                        }
                        if (orderIdListNew.size() == 0){
                            orderIdList.add(tcwFinancesApiInFoId);
                        }
                        if (!FinancialEventsType.TRANSFER.getCode().equals(tcwFinancesApiData.getType())){
                            //二次金额相加
                            tcwFinancesEventGroups.setTwoCurrencyAmount(tcwFinancesEventGroups.getTwoCurrencyAmount().add(tcwFinancesApiData.getTotal()));
                        }
                    }
                    //RemovalShipmentEventList 移除发货事件信息列表
                    if (FinancialEventsType.REMOVALSHIPMENTADJUSTMENTEVENTLIST.getCode().equals(tcwFinancesApiData.getType())) {
                        orderListNew = orderList.stream().filter(tcwFinancesApiInFoNew -> FinancialEventsType.REMOVALSHIPMENTADJUSTMENTEVENTLIST.getCode().equals(tcwFinancesApiInFoNew.getType())
                                && tcwFinancesApiData.getSku().equals(tcwFinancesApiInFoNew.getSku())
                                && tcwFinancesApiData.getFinancialEventGroupId().equals(tcwFinancesApiInFoNew.getFinancialEventGroupId()))
                                .collect(Collectors.toList());
                        if (orderListNew.size() == 0) {
                            tcwFinancesApiInFo = new TcwFinancesApiInFo();
                            setInFo(tcwFinancesApiInFo,tcwFinancesEventGroups);
                            tcwFinancesApiInFo.setType(tcwFinancesApiData.getType());
                            tcwFinancesApiInFo.setSku(tcwFinancesApiData.getSku());
                            tcwFinancesApiInFo.setFinancialEventGroupId(tcwFinancesApiData.getFinancialEventGroupId());
                            tcwFinancesApiInFo.setGroupId(tcwFinancesApiData.getGroupId());
                            tcwFinancesApiInFo.setPurchaseDate(tcwFinancesApiData.getPurchaseDate());
                            tcwFinancesApiInFo.setDataType(tcwFinancesApiData.getDataType());
                            tcwFinancesApiInFo.setThereDataType("Liquidations Adjustments");
                            //设置商品名称
                            getProductCode(tcwFinancesApiData,tpAmazonShopProductList, tcwFinancesEventGroups,tcwFinancesApiInFo);
                        }else {
                            tcwFinancesApiInFo = orderListNew.get(0);
                        }

                        orderIdListNew = orderIdList.stream().filter(tcwFinancesApiInFoNew -> FinancialEventsType.REMOVALSHIPMENTADJUSTMENTEVENTLIST.getCode().equals(tcwFinancesApiInFoNew.getType())
                                && tcwFinancesApiData.getSku().equals(tcwFinancesApiInFoNew.getSku())
                                && tcwFinancesApiData.getFinancialEventGroupId().equals(tcwFinancesApiInFoNew.getFinancialEventGroupId()))
                                .collect(Collectors.toList());
                        if (orderIdListNew.size() == 0){
                            tcwFinancesApiInFoId = new TcwFinancesApiInFoId();
                            setInFoId(tcwFinancesApiInFoId,tcwFinancesEventGroups);
                            tcwFinancesApiInFoId.setType(tcwFinancesApiData.getType());
                            tcwFinancesApiInFoId.setSku(tcwFinancesApiData.getSku());
                            tcwFinancesApiInFoId.setFinancialEventGroupId(tcwFinancesApiData.getFinancialEventGroupId());
                            tcwFinancesApiInFoId.setGroupId(tcwFinancesApiData.getGroupId());
                            tcwFinancesApiInFoId.setPurchaseDate(tcwFinancesApiData.getPurchaseDate());
                            tcwFinancesApiInFoId.setDataType(tcwFinancesApiData.getDataType());
                            tcwFinancesApiInFoId.setThereDataType(tcwFinancesApiData.getThereDataType());
                            tcwFinancesApiInFoId.setAmazonOrderId(tcwFinancesApiData.getAmazonOrderId());
                            //设置商品名称
                            getProductCodeId(tcwFinancesApiData,tpAmazonShopProductList, tcwFinancesEventGroups,tcwFinancesApiInFoId);
                        }else {
                            tcwFinancesApiInFoId = orderIdListNew.get(0);
                        }

                        //revenueAdjustment
                        if (FinancialEventsType.WHOLESALE_LIQUIDATION.getCode().equals(tcwFinancesApiData.getDataType())
                                && FinancialEventsType.REVENUEADJUSTMENT.getCode().equals(tcwFinancesApiData.getThereDataType())){
                            tcwFinancesApiInFo.setQuantity(tcwFinancesApiInFo.getQuantity() + tcwFinancesApiData.getQuantity());
                            tcwFinancesApiInFoId.setQuantity(tcwFinancesApiInFoId.getQuantity() + tcwFinancesApiData.getQuantity());
                        }
                        //总金额
                        tcwFinancesApiInFo.setTotal(tcwFinancesApiInFo.getTotal().add(tcwFinancesApiData.getTotal()));
                        tcwFinancesApiInFoId.setTotal(tcwFinancesApiInFoId.getTotal().add(tcwFinancesApiData.getTotal()));
                        if (orderListNew.size() == 0){
                            orderList.add(tcwFinancesApiInFo);
                        }
                        if (orderIdListNew.size() == 0){
                            orderIdList.add(tcwFinancesApiInFoId);
                        }
                        if (!FinancialEventsType.TRANSFER.getCode().equals(tcwFinancesApiData.getType())){
                            //二次金额相加
                            tcwFinancesEventGroups.setTwoCurrencyAmount(tcwFinancesEventGroups.getTwoCurrencyAmount().add(tcwFinancesApiData.getTotal()));
                        }
                    }
                    //TrialShipmentEventList 有关试运财务事件的信息列表
                    addFinancesApiInFo(orderList,FinancialEventsType.TRIALSHIPMENTEVENTLIST.getCode(),tcwFinancesApiData.getType(),tcwFinancesApiData,tcwFinancesEventGroups,tpAmazonShopProductList,orderIdList);
                    // TaxWithholdingEventList 	预扣税事件列表
                    addFinancesApiInFo(orderList,FinancialEventsType.TAXWITHHOLDINGEVENTLIST.getCode(),tcwFinancesApiData.getType(),tcwFinancesApiData,tcwFinancesEventGroups,tpAmazonShopProductList,orderIdList);

                    //TDSReimbursementEventList TDS报销事件列表
                    addFinancesApiInFo(orderList,FinancialEventsType.TDSREIMBURSEMENTEVENTLIST.getCode(),tcwFinancesApiData.getType(),tcwFinancesApiData,tcwFinancesEventGroups,tpAmazonShopProductList,orderIdList);
                    //AdhocDisbursementEventList 临时支付事件列表
                    addFinancesApiInFo(orderList,FinancialEventsType.ADHOCDISBURSEMENTEVENTLIST.getCode(),tcwFinancesApiData.getType(),tcwFinancesApiData,tcwFinancesEventGroups,tpAmazonShopProductList,orderIdList);
                    //ChargeRefundEventList 充值退款活动列表
                    addFinancesApiInFo(orderList,FinancialEventsType.CHARGEREFUNDEVENTLIST.getCode(),tcwFinancesApiData.getType(),tcwFinancesApiData,tcwFinancesEventGroups,tpAmazonShopProductList,orderIdList);
                    //FailedAdhocDisbursementEventList 失败的临时支付事件列表
                    addFinancesApiInFo(orderList,FinancialEventsType.FAILEDADHOCDISBURSEMENTEVENTLIST.getCode(),tcwFinancesApiData.getType(),tcwFinancesApiData,tcwFinancesEventGroups,tpAmazonShopProductList,orderIdList);
                    //ValueAddedServiceChargeEventList 与增值服务费相关的事件。。
                    addFinancesApiInFo(orderList,FinancialEventsType.VALUEADDEDSERVICECHARGEEVENTLIST.getCode(),tcwFinancesApiData.getType(),tcwFinancesApiData,tcwFinancesEventGroups,tpAmazonShopProductList,orderIdList);
                    //CapacityReservationBillingEventList 容量预留计费事件列表。。
                    addFinancesApiInFo(orderList,FinancialEventsType.CAPACITYRESERVATIONBILLINGEVENTLIST.getCode(),tcwFinancesApiData.getType(),tcwFinancesApiData,tcwFinancesEventGroups,tpAmazonShopProductList,orderIdList);
                }
                tcwFinancesEventGroupsMapper.update(tcwFinancesEventGroups);
                int insertLength = orderList.size();
                int i = 0;
                while (insertLength > 50) {
                    diySqlMapper.insertBatchTcwFinancesInfo(orderList.subList(i, i + 50));
                    i = i + 50;
                    insertLength = insertLength - 50;
                }
                if (insertLength > 0) {
                    diySqlMapper.insertBatchTcwFinancesInfo(orderList.subList(i, i + insertLength));
                }

                int insertIdLength = orderIdList.size();
                int j = 0;
                while (insertIdLength > 50) {
                    diySqlMapper.insertBatchTcwFinancesInfoId(orderIdList.subList(j, j + 50));
                    j = j + 50;
                    insertIdLength = insertIdLength - 50;
                }
                if (insertIdLength > 0) {
                    diySqlMapper.insertBatchTcwFinancesInfoId(orderIdList.subList(j, j + insertIdLength));
                }
            }
        }catch (Exception ex) {
            apiResponse.setCode(500);
            apiResponse.setMessage("ECP_API调用获取亚马逊二次财务数据相关信息接口出错，具体错误信息为：" + ex.getMessage());
        }
        logger.info("***********每月定时新增财务事件明细新增成功，***********");
        return apiResponse;
    }

    /**
     * 订单事件信息
     */
    private List<TcwFinancesApiInFo> addOrder(String code,String type,TcwFinancesApiData tcwFinancesApiData,List<TcwFinancesApiInFo> orderList
            ,String thereDataType,TcwFinancesEventGroups tcwFinancesEventGroups,List<Map<String, Object>> tpAmazonShopProductList,List<TcwFinancesApiInFoId> orderListId){
        if (code.equals(type)){
            TcwFinancesApiInFo tcwFinancesApiInFo;
            String sku = tcwFinancesApiData.getSku() == null ? "": tcwFinancesApiData.getSku();
            List<TcwFinancesApiInFo> orderListNew = orderList.stream().filter(tcwFinancesApiInFoNew -> code.equals(tcwFinancesApiInFoNew.getType())
                    && sku.equals(tcwFinancesApiInFoNew.getSku())
                    && tcwFinancesApiData.getFinancialEventGroupId().equals(tcwFinancesApiInFoNew.getFinancialEventGroupId()))
                    .collect(Collectors.toList());
            if (orderListNew.size() == 0){
                tcwFinancesApiInFo = new TcwFinancesApiInFo();
                setInFo(tcwFinancesApiInFo,tcwFinancesEventGroups);
                tcwFinancesApiInFo.setType(tcwFinancesApiData.getType());
                tcwFinancesApiInFo.setSku(tcwFinancesApiData.getSku());
                tcwFinancesApiInFo.setFinancialEventGroupId(tcwFinancesApiData.getFinancialEventGroupId());
                tcwFinancesApiInFo.setGroupId(tcwFinancesApiData.getGroupId());
                tcwFinancesApiInFo.setPurchaseDate(tcwFinancesApiData.getPurchaseDate());
                tcwFinancesApiInFo.setDataType(tcwFinancesApiData.getDataType());
                tcwFinancesApiInFo.setThereDataType(thereDataType);
                //设置商品名称
                getProductCode(tcwFinancesApiData,tpAmazonShopProductList, tcwFinancesEventGroups,tcwFinancesApiInFo);
            }else {
                tcwFinancesApiInFo = orderListNew.get(0);
            }

            //订单详情表多一个订单的判断维度
            TcwFinancesApiInFoId tcwFinancesApiInFoId;
            String amazonOrderId = tcwFinancesApiData.getAmazonOrderId() == null ? "": tcwFinancesApiData.getAmazonOrderId();
            List<TcwFinancesApiInFoId> orderListIdNew = orderListId.stream().filter(tcwFinancesApiInFoNew -> code.equals(tcwFinancesApiInFoNew.getType())
                    && sku.equals(tcwFinancesApiInFoNew.getSku())
                    && amazonOrderId.equals(tcwFinancesApiInFoNew.getAmazonOrderId())
                    && tcwFinancesApiData.getFinancialEventGroupId().equals(tcwFinancesApiInFoNew.getFinancialEventGroupId()))
                    .collect(Collectors.toList());
            if (orderListIdNew.size() == 0){
                tcwFinancesApiInFoId = new TcwFinancesApiInFoId();
                setInFoId(tcwFinancesApiInFoId,tcwFinancesEventGroups);
                tcwFinancesApiInFoId.setType(tcwFinancesApiData.getType());
                tcwFinancesApiInFoId.setSku(tcwFinancesApiData.getSku());
                tcwFinancesApiInFoId.setFinancialEventGroupId(tcwFinancesApiData.getFinancialEventGroupId());
                tcwFinancesApiInFoId.setGroupId(tcwFinancesApiData.getGroupId());
                tcwFinancesApiInFoId.setPurchaseDate(tcwFinancesApiData.getPurchaseDate());
                tcwFinancesApiInFoId.setDataType(tcwFinancesApiData.getDataType());
                tcwFinancesApiInFoId.setThereDataType(thereDataType);
                tcwFinancesApiInFoId.setAmazonOrderId(tcwFinancesApiData.getAmazonOrderId());
                //设置商品名称
                getProductCodeId(tcwFinancesApiData,tpAmazonShopProductList, tcwFinancesEventGroups,tcwFinancesApiInFoId);
            }else {
                tcwFinancesApiInFoId = orderListIdNew.get(0);
            }

            Boolean flx = false;
            //Principal 本金
            if (FinancialEventsType.ITEMCHARGELIST.getCode().equals(tcwFinancesApiData.getDataType())
                    && FinancialEventsType.PRINCIPAL.getCode().equals(tcwFinancesApiData.getThereDataType())){
                tcwFinancesApiInFo.setProductSales(tcwFinancesApiInFo.getProductSales().add(tcwFinancesApiData.getTotal()));

                //Quantity 数量
                tcwFinancesApiInFo.setQuantity(tcwFinancesApiInFo.getQuantity() + tcwFinancesApiData.getQuantity());

                tcwFinancesApiInFoId.setProductSales(tcwFinancesApiInFoId.getProductSales().add(tcwFinancesApiData.getTotal()));
                tcwFinancesApiInFoId.setQuantity(tcwFinancesApiInFoId.getQuantity() + tcwFinancesApiData.getQuantity());
                flx =true;
            }else if (FinancialEventsType.ITEMCHARGELIST.getCode().equals(tcwFinancesApiData.getDataType())
                    && FinancialEventsType.TAX.getCode().equals(tcwFinancesApiData.getThereDataType())){
                //Tax 本金税收
                tcwFinancesApiInFo.setProductSalesTax(tcwFinancesApiInFo.getProductSalesTax().add(tcwFinancesApiData.getTotal()));
                tcwFinancesApiInFoId.setProductSalesTax(tcwFinancesApiInFoId.getProductSalesTax().add(tcwFinancesApiData.getTotal()));
                flx =true;
            }else if (FinancialEventsType.ITEMCHARGELIST.getCode().equals(tcwFinancesApiData.getDataType())
                    && FinancialEventsType.SHIPPINGCHARGE.getCode().equals(tcwFinancesApiData.getThereDataType())){
                //ShippingCharge 运费
                tcwFinancesApiInFo.setPostageCredits(tcwFinancesApiInFo.getPostageCredits().add(tcwFinancesApiData.getTotal()));
                tcwFinancesApiInFoId.setPostageCredits(tcwFinancesApiInFoId.getPostageCredits().add(tcwFinancesApiData.getTotal()));
                flx =true;
            }else if (FinancialEventsType.ITEMCHARGELIST.getCode().equals(tcwFinancesApiData.getDataType())
                    && FinancialEventsType.SHIPPINGTAX.getCode().equals(tcwFinancesApiData.getThereDataType())){
                //ShippingTax 运费税收
                tcwFinancesApiInFo.setShippingCreditsTax(tcwFinancesApiInFo.getShippingCreditsTax().add(tcwFinancesApiData.getTotal()));
                tcwFinancesApiInFoId.setShippingCreditsTax(tcwFinancesApiInFoId.getShippingCreditsTax().add(tcwFinancesApiData.getTotal()));
                flx =true;
            }else if (FinancialEventsType.ITEMCHARGELIST.getCode().equals(tcwFinancesApiData.getDataType())
                    && FinancialEventsType.GIFTWRAP.getCode().equals(tcwFinancesApiData.getThereDataType())){
                //GiftWrap 礼品包装费
                tcwFinancesApiInFo.setGiftWrapCredits(tcwFinancesApiInFo.getGiftWrapCredits().add(tcwFinancesApiData.getTotal()));
                tcwFinancesApiInFoId.setGiftWrapCredits(tcwFinancesApiInFoId.getGiftWrapCredits().add(tcwFinancesApiData.getTotal()));
                flx =true;
            }else if (FinancialEventsType.ITEMCHARGELIST.getCode().equals(tcwFinancesApiData.getDataType())
                    && FinancialEventsType.GIFTWRAPTAX.getCode().equals(tcwFinancesApiData.getThereDataType())){
                //GiftWrapTax 礼品包装费税收
                tcwFinancesApiInFo.setGiftwrapCreditsTax(tcwFinancesApiInFo.getGiftwrapCreditsTax().add(tcwFinancesApiData.getTotal()));
                tcwFinancesApiInFoId.setGiftwrapCreditsTax(tcwFinancesApiInFoId.getGiftwrapCreditsTax().add(tcwFinancesApiData.getTotal()));
                flx =true;
            }else if (FinancialEventsType.PROMOTIONLIST.getCode().equals(tcwFinancesApiData.getDataType())
                    && FinancialEventsType.PROMOTIONALREBATESTAX.getCode().equals(tcwFinancesApiData.getThereDataType())){
                // promotionalRebatesTax 促销费税收
                tcwFinancesApiInFo.setPromotionalRebatesTax(tcwFinancesApiInFo.getPromotionalRebatesTax().add(tcwFinancesApiData.getTotal()));
                tcwFinancesApiInFoId.setPromotionalRebatesTax(tcwFinancesApiInFoId.getPromotionalRebatesTax().add(tcwFinancesApiData.getTotal()));
                flx =true;
            }else if (FinancialEventsType.PROMOTIONLIST.getCode().equals(tcwFinancesApiData.getDataType())
                    && FinancialEventsType.PROMOTIONALREBATES.getCode().equals(tcwFinancesApiData.getThereDataType())){
                //promotionalRebates 促销费
                tcwFinancesApiInFo.setPromotionalRebates(tcwFinancesApiInFo.getPromotionalRebates().add(tcwFinancesApiData.getTotal()));
                tcwFinancesApiInFoId.setPromotionalRebates(tcwFinancesApiInFoId.getPromotionalRebates().add(tcwFinancesApiData.getTotal()));
                flx =true;
            }else if (FinancialEventsType.ITEMTAXWITHHELDLIST.getCode().equals(tcwFinancesApiData.getDataType())
                    && FinancialEventsType.MARKETPLACEFACILITATOR.getCode().equals(tcwFinancesApiData.getThereDataType())){
                // MarketplaceFacilitator 代缴税收
                tcwFinancesApiInFo.setMarketplaceWithheldTax(tcwFinancesApiInFo.getMarketplaceWithheldTax().add(tcwFinancesApiData.getTotal()));
                tcwFinancesApiInFoId.setMarketplaceWithheldTax(tcwFinancesApiInFoId.getMarketplaceWithheldTax().add(tcwFinancesApiData.getTotal()));
                flx =true;
            }else if (FinancialEventsType.ITEMFEELIST.getCode().equals(tcwFinancesApiData.getDataType())
                    && (FinancialEventsType.COMMISSION.getCode().equals(tcwFinancesApiData.getThereDataType())
                    || FinancialEventsType.REFUNDCOMMISSION.getCode().equals(tcwFinancesApiData.getThereDataType()))){
                //销售费用(Commission + RefundCommission)
                tcwFinancesApiInFo.setSellingFees(tcwFinancesApiInFo.getSellingFees().add(tcwFinancesApiData.getTotal()));
                tcwFinancesApiInFoId.setSellingFees(tcwFinancesApiInFoId.getSellingFees().add(tcwFinancesApiData.getTotal()));
                flx =true;
            }else if (FinancialEventsType.ITEMFEELIST.getCode().equals(tcwFinancesApiData.getDataType())
                    && (FinancialEventsType.FBAPERUNITFULFILLMENTFEE.getCode().equals(tcwFinancesApiData.getThereDataType())
                    || FinancialEventsType.SHIPPINGCHARGEBACK.getCode().equals(tcwFinancesApiData.getThereDataType()))){
                //Fba费用 （ShippingChargeback + FBAPerUnitFulfillmentFee）
                tcwFinancesApiInFo.setFbaFees(tcwFinancesApiInFo.getFbaFees().add(tcwFinancesApiData.getTotal()));
                tcwFinancesApiInFoId.setFbaFees(tcwFinancesApiInFoId.getFbaFees().add(tcwFinancesApiData.getTotal()));
                flx =true;
            }else if (FinancialEventsType.ITEMFEELIST.getCode().equals(tcwFinancesApiData.getDataType())
                    && FinancialEventsType.GIFTWRAPCHARGEBACK.getCode().equals(tcwFinancesApiData.getThereDataType())){
                //GiftwrapChargeback 礼品包装回收费
                tcwFinancesApiInFo.setGiftwrapChargeback(tcwFinancesApiInFo.getGiftwrapChargeback().add(tcwFinancesApiData.getTotal()));
                tcwFinancesApiInFoId.setGiftwrapChargeback(tcwFinancesApiInFoId.getGiftwrapChargeback().add(tcwFinancesApiData.getTotal()));
                flx =true;
            }else if (FinancialEventsType.ITEMCHARGELIST.getCode().equals(tcwFinancesApiData.getDataType())
                    && FinancialEventsType.RESTOCKINGFEE.getCode().equals(tcwFinancesApiData.getThereDataType())){
                //RestockingFee 重装补偿费
                tcwFinancesApiInFo.setRestockingFee(tcwFinancesApiInFo.getRestockingFee().add(tcwFinancesApiData.getTotal()));
                tcwFinancesApiInFoId.setRestockingFee(tcwFinancesApiInFoId.getRestockingFee().add(tcwFinancesApiData.getTotal()));
                flx =true;
            }else if (FinancialEventsType.ITEMFEELIST.getCode().equals(tcwFinancesApiData.getDataType())
                    && FinancialEventsType.VARIABLECLOSINGFEE.getCode().equals(tcwFinancesApiData.getThereDataType())){
                //VariableClosingFee 浮动销售手续费
                tcwFinancesApiInFo.setVariableClosingFee(tcwFinancesApiInFo.getVariableClosingFee().add(tcwFinancesApiData.getTotal()));
                tcwFinancesApiInFoId.setVariableClosingFee(tcwFinancesApiInFoId.getVariableClosingFee().add(tcwFinancesApiData.getTotal()));
                flx =true;
            }else if (FinancialEventsType.ITEMCHARGELIST.getCode().equals(tcwFinancesApiData.getDataType())
                    && FinancialEventsType.GOODWILL.getCode().equals(tcwFinancesApiData.getThereDataType())){
                //Goodwill 妥协费
                tcwFinancesApiInFo.setGoodwill(tcwFinancesApiInFo.getGoodwill().add(tcwFinancesApiData.getTotal()));
                tcwFinancesApiInFoId.setGoodwill(tcwFinancesApiInFoId.getGoodwill().add(tcwFinancesApiData.getTotal()));
                flx =true;
            }else if (FinancialEventsType.ITEMTAXWITHHELDLIST.getCode().equals(tcwFinancesApiData.getDataType())
                    && FinancialEventsType.LOWVALUEGOODS.getCode().equals(tcwFinancesApiData.getThereDataType())){
                //LowValueGoods 低价促销费用
                tcwFinancesApiInFo.setLowValueGoods(tcwFinancesApiInFo.getLowValueGoods().add(tcwFinancesApiData.getTotal()));
                tcwFinancesApiInFoId.setLowValueGoods(tcwFinancesApiInFoId.getLowValueGoods().add(tcwFinancesApiData.getTotal()));
                flx =true;
            }else if (FinancialEventsType.ITEMFEELIST.getCode().equals(tcwFinancesApiData.getDataType())
                    && FinancialEventsType.GETPAIDFASTERFEE.getCode().equals(tcwFinancesApiData.getThereDataType())){
                //GetPaidFasterFee 快速收款手续费
                tcwFinancesApiInFo.setGetPaidFasterFee(tcwFinancesApiInFo.getGetPaidFasterFee().add(tcwFinancesApiData.getTotal()));
                tcwFinancesApiInFoId.setGetPaidFasterFee(tcwFinancesApiInFoId.getGetPaidFasterFee().add(tcwFinancesApiData.getTotal()));
                flx =true;
            }else if (FinancialEventsType.ITEMFEELIST.getCode().equals(tcwFinancesApiData.getDataType())
                    && FinancialEventsType.SHIPPINGHB.getCode().equals(tcwFinancesApiData.getThereDataType())){
                //ShippingHB
                tcwFinancesApiInFo.setShippingHB(tcwFinancesApiInFo.getShippingHB().add(tcwFinancesApiData.getTotal()));
                tcwFinancesApiInFoId.setShippingHB(tcwFinancesApiInFoId.getShippingHB().add(tcwFinancesApiData.getTotal()));
                flx =true;
            }else {
                //其他还未知的金额存储
                tcwFinancesApiInFo.setSurplus(tcwFinancesApiInFo.getSurplus().add(tcwFinancesApiData.getTotal()));
                tcwFinancesApiInFoId.setSurplus(tcwFinancesApiInFo.getSurplus().add(tcwFinancesApiData.getTotal()));
            }
            //总金额
            tcwFinancesApiInFo.setTotal(tcwFinancesApiInFo.getTotal().add(tcwFinancesApiData.getTotal()));
            tcwFinancesApiInFoId.setTotal(tcwFinancesApiInFoId.getTotal().add(tcwFinancesApiData.getTotal()));
            if (orderListNew.size() == 0){
                orderList.add(tcwFinancesApiInFo);
            }
            if (orderListIdNew.size() == 0){
                orderListId.add(tcwFinancesApiInFoId);
            }
            if (!FinancialEventsType.TRANSFER.getCode().equals(type)){
                if (flx){
                    //二次金额相加
                    tcwFinancesEventGroups.setTwoCurrencyAmount(tcwFinancesEventGroups.getTwoCurrencyAmount().add(tcwFinancesApiData.getTotal()));
                }
            }
        }
        return orderList;
    }

    /**
     * 添加二次财务金额
     */
    private List<TcwFinancesApiInFo> addFinancesApiInFo(List<TcwFinancesApiInFo> orderList,String code, String type,TcwFinancesApiData tcwFinancesApiData,
                                                        TcwFinancesEventGroups tcwFinancesEventGroups,List<Map<String, Object>> tpAmazonShopProductList,List<TcwFinancesApiInFoId> orderListId){
        if (code.equals(type)){
            TcwFinancesApiInFo tcwFinancesApiInFo = new TcwFinancesApiInFo();
            setInFo(tcwFinancesApiInFo,tcwFinancesEventGroups);
            BeanUtils.copyProperties(tcwFinancesApiData,tcwFinancesApiInFo);
            if (!FinancialEventsType.TRANSFER.getCode().equals(tcwFinancesApiData.getType())){
                //二次金额相加
                tcwFinancesEventGroups.setTwoCurrencyAmount(tcwFinancesEventGroups.getTwoCurrencyAmount().add(tcwFinancesApiData.getTotal()));
                //设置商品名称
                getProductCode(tcwFinancesApiData,tpAmazonShopProductList, tcwFinancesEventGroups,tcwFinancesApiInFo);
            }
            orderList.add(tcwFinancesApiInFo);

            TcwFinancesApiInFoId tcwFinancesApiInFoId = new TcwFinancesApiInFoId();
            BeanUtils.copyProperties(tcwFinancesApiInFo,tcwFinancesApiInFoId);
            tcwFinancesApiInFoId.setAmazonOrderId(tcwFinancesApiData.getAmazonOrderId());
            orderListId.add(tcwFinancesApiInFoId);
        }
        return orderList;
    }


    /**
     * 设置商品名称
     * @param tcwFinancesApiData
     */
    private TcwFinancesApiInFo getProductCode(TcwFinancesApiData tcwFinancesApiData,List<Map<String, Object>> tpAmazonShopProductList,
                                TcwFinancesEventGroups tcwFinancesEventGroups,TcwFinancesApiInFo tcwFinancesApiInFo){
        if (tcwFinancesApiData.getSku() != null){
            List<Map<String, Object>> tpAmazonShopProductListNew = null;
            //商品名称
            tpAmazonShopProductListNew = tpAmazonShopProductList.stream()
                    .filter(item->item.get("shopGuid").equals(tcwFinancesEventGroups.getShopGuid())
                    && (item.get("sellerSku").equals(tcwFinancesApiData.getSku()) || item.get("asin").equals(tcwFinancesApiData.getSku())))
                    .collect(Collectors.toList());
            if (tpAmazonShopProductListNew.size() != 0){
                tcwFinancesApiInFo.setProductCode(String.valueOf(tpAmazonShopProductListNew.get(0).get("code")));
                tcwFinancesApiInFo.setProductName(tpAmazonShopProductListNew.get(0).get("name") == null ? null:String.valueOf(tpAmazonShopProductListNew.get(0).get("name")));
            }
        }
        return tcwFinancesApiInFo;
    }

    private TcwFinancesApiInFoId getProductCodeId(TcwFinancesApiData tcwFinancesApiData,List<Map<String, Object>> tpAmazonShopProductList,
                                              TcwFinancesEventGroups tcwFinancesEventGroups,TcwFinancesApiInFoId tcwFinancesApiInFoId){
        if (tcwFinancesApiData.getSku() != null){
            List<Map<String, Object>> tpAmazonShopProductListNew = null;
            //商品名称
            tpAmazonShopProductListNew = tpAmazonShopProductList.stream()
                    .filter(item->item.get("shopGuid").equals(tcwFinancesEventGroups.getShopGuid())
                            && (item.get("sellerSku").equals(tcwFinancesApiData.getSku()) || item.get("asin").equals(tcwFinancesApiData.getSku())))
                    .collect(Collectors.toList());
            if (tpAmazonShopProductListNew.size() != 0){
                tcwFinancesApiInFoId.setProductCode(String.valueOf(tpAmazonShopProductListNew.get(0).get("code")));
                tcwFinancesApiInFoId.setProductName(tpAmazonShopProductListNew.get(0).get("name") == null ? null:String.valueOf(tpAmazonShopProductListNew.get(0).get("name")));
            }
        }
        return tcwFinancesApiInFoId;
    }

    private TcwFinancesApiInFo setInFo(TcwFinancesApiInFo tcwFinancesApiInFo,TcwFinancesEventGroups tcwFinancesEventGroups){
        tcwFinancesApiInFo.setQuantity(0);
        tcwFinancesApiInFo.setProductSales(BigDecimal.ZERO);
        tcwFinancesApiInFo.setProductSalesTax(BigDecimal.ZERO);
        tcwFinancesApiInFo.setPostageCredits(BigDecimal.ZERO);
        tcwFinancesApiInFo.setShippingCreditsTax(BigDecimal.ZERO);
        tcwFinancesApiInFo.setGiftWrapCredits(BigDecimal.ZERO);
        tcwFinancesApiInFo.setGiftwrapCreditsTax(BigDecimal.ZERO);
        tcwFinancesApiInFo.setPromotionalRebates(BigDecimal.ZERO);
        tcwFinancesApiInFo.setPromotionalRebatesTax(BigDecimal.ZERO);
        tcwFinancesApiInFo.setMarketplaceWithheldTax(BigDecimal.ZERO);
        tcwFinancesApiInFo.setSellingFees(BigDecimal.ZERO);
        tcwFinancesApiInFo.setFbaFees(BigDecimal.ZERO);
        tcwFinancesApiInFo.setOtherTransactionFees(BigDecimal.ZERO);
        tcwFinancesApiInFo.setOther(BigDecimal.ZERO);
        tcwFinancesApiInFo.setTotal(BigDecimal.ZERO);
        tcwFinancesApiInFo.setGiftwrapChargeback(BigDecimal.ZERO);
        tcwFinancesApiInFo.setRestockingFee(BigDecimal.ZERO);
        tcwFinancesApiInFo.setVariableClosingFee(BigDecimal.ZERO);
        tcwFinancesApiInFo.setGoodwill(BigDecimal.ZERO);
        tcwFinancesApiInFo.setLowValueGoods(BigDecimal.ZERO);
        tcwFinancesApiInFo.setGetPaidFasterFee(BigDecimal.ZERO);
        tcwFinancesApiInFo.setShippingHB(BigDecimal.ZERO);
        tcwFinancesApiInFo.setSurplus(BigDecimal.ZERO);
        tcwFinancesApiInFo.setStartDate(tcwFinancesEventGroups.getStartDate());
        tcwFinancesApiInFo.setEndDate(tcwFinancesEventGroups.getEndDate());
        tcwFinancesApiInFo.setCurrencyCode(tcwFinancesEventGroups.getCurrencyCode());
        tcwFinancesApiInFo.setCurrency(tcwFinancesEventGroups.getCurrency());
        tcwFinancesApiInFo.setShopNameMc(tcwFinancesEventGroups.getShopNameMc());
        tcwFinancesApiInFo.setCompanyID(tcwFinancesEventGroups.getCompanyID());
        tcwFinancesApiInFo.setShopName(tcwFinancesEventGroups.getShopName());
        return tcwFinancesApiInFo;
    }

    private TcwFinancesApiInFoId setInFoId(TcwFinancesApiInFoId tcwFinancesApiInFoId,TcwFinancesEventGroups tcwFinancesEventGroups){
        tcwFinancesApiInFoId.setQuantity(0);
        tcwFinancesApiInFoId.setProductSales(BigDecimal.ZERO);
        tcwFinancesApiInFoId.setProductSalesTax(BigDecimal.ZERO);
        tcwFinancesApiInFoId.setPostageCredits(BigDecimal.ZERO);
        tcwFinancesApiInFoId.setShippingCreditsTax(BigDecimal.ZERO);
        tcwFinancesApiInFoId.setGiftWrapCredits(BigDecimal.ZERO);
        tcwFinancesApiInFoId.setGiftwrapCreditsTax(BigDecimal.ZERO);
        tcwFinancesApiInFoId.setPromotionalRebates(BigDecimal.ZERO);
        tcwFinancesApiInFoId.setPromotionalRebatesTax(BigDecimal.ZERO);
        tcwFinancesApiInFoId.setMarketplaceWithheldTax(BigDecimal.ZERO);
        tcwFinancesApiInFoId.setSellingFees(BigDecimal.ZERO);
        tcwFinancesApiInFoId.setFbaFees(BigDecimal.ZERO);
        tcwFinancesApiInFoId.setOtherTransactionFees(BigDecimal.ZERO);
        tcwFinancesApiInFoId.setOther(BigDecimal.ZERO);
        tcwFinancesApiInFoId.setTotal(BigDecimal.ZERO);
        tcwFinancesApiInFoId.setGiftwrapChargeback(BigDecimal.ZERO);
        tcwFinancesApiInFoId.setRestockingFee(BigDecimal.ZERO);
        tcwFinancesApiInFoId.setVariableClosingFee(BigDecimal.ZERO);
        tcwFinancesApiInFoId.setGoodwill(BigDecimal.ZERO);
        tcwFinancesApiInFoId.setLowValueGoods(BigDecimal.ZERO);
        tcwFinancesApiInFoId.setGetPaidFasterFee(BigDecimal.ZERO);
        tcwFinancesApiInFoId.setShippingHB(BigDecimal.ZERO);
        tcwFinancesApiInFoId.setAmazonOrderId(null);
        tcwFinancesApiInFoId.setSurplus(BigDecimal.ZERO);
        tcwFinancesApiInFoId.setStartDate(tcwFinancesEventGroups.getStartDate());
        tcwFinancesApiInFoId.setEndDate(tcwFinancesEventGroups.getEndDate());
        tcwFinancesApiInFoId.setCurrencyCode(tcwFinancesEventGroups.getCurrencyCode());
        tcwFinancesApiInFoId.setCurrency(tcwFinancesEventGroups.getCurrency());
        tcwFinancesApiInFoId.setShopNameMc(tcwFinancesEventGroups.getShopNameMc());
        tcwFinancesApiInFoId.setCompanyID(tcwFinancesEventGroups.getCompanyID());
        tcwFinancesApiInFoId.setShopName(tcwFinancesEventGroups.getShopName());
        return tcwFinancesApiInFoId;
    }


    /**
     * 添加财务api数据
     */
    private List<TcwFinancesApiData> addTcwF(List<TcwFinancesApiData> tcwFinancesApiDataList,String type,String dataType,String thereDataType,String sku,Integer quantity, BigDecimal total,
                                             String financialEventGroupId,String amazonOrderId, Date purchaseDate,String amountsJson
            , TcwFinancesEventGroups tcwFinancesEventGroups){
        TcwFinancesApiData tcwFinancesApiData = new TcwFinancesApiData();
        tcwFinancesApiData.setType(type);
        tcwFinancesApiData.setDataType(dataType);
        tcwFinancesApiData.setThereDataType(thereDataType);
        tcwFinancesApiData.setSku(sku);
        tcwFinancesApiData.setQuantity(quantity);
        tcwFinancesApiData.setTotal(total);
        tcwFinancesApiData.setFinancialEventGroupId(financialEventGroupId);
        tcwFinancesApiData.setGroupId(String.valueOf(tcwFinancesEventGroups.getId()));
        tcwFinancesApiData.setAmazonOrderId(amazonOrderId);
        tcwFinancesApiData.setAmountsJson(amountsJson);
        tcwFinancesApiData.setPurchaseDate(purchaseDate);
        tcwFinancesApiDataList.add(tcwFinancesApiData);
        if (!"Transfer".equals(dataType)){
            tcwFinancesEventGroups.setXjCurrencyAmount(tcwFinancesEventGroups.getXjCurrencyAmount().add(total));
        }
        return tcwFinancesApiDataList;
    }

    private List<TcwFinancesApiData> addShipmentEventOrAdjustment(List<TcwFinancesApiData> tcwFinancesApiDataList,ShipmentEvent shipmentEvent
            ,TcwFinancesEventGroups tcwFinancesEventGroups,FinancialEventGroup financialEventGroup
            ,Date postedDate,String code ){
        if (shipmentEvent.getShipmentItemList() !=  null) {
            //回填店铺信息
            if (tcwFinancesEventGroups.getMarketplaceName() == null){
                tcwFinancesEventGroups.setMarketplaceName(shipmentEvent.getMarketplaceName());
                tcwFinancesEventGroupsMapper.update(tcwFinancesEventGroups);
            }
            addShipmentEvent(tcwFinancesApiDataList,shipmentEvent,tcwFinancesEventGroups,financialEventGroup,postedDate,code);
        }
        if (shipmentEvent.getShipmentItemAdjustmentList() != null) {
            //回填店铺信息
            if (tcwFinancesEventGroups.getMarketplaceName() == null){
                tcwFinancesEventGroups.setMarketplaceName(shipmentEvent.getMarketplaceName());
                tcwFinancesEventGroupsMapper.update(tcwFinancesEventGroups);
            }
            getShipmentItemAdjustmentList(tcwFinancesApiDataList,shipmentEvent,tcwFinancesEventGroups,financialEventGroup,postedDate,code);
        }
        return tcwFinancesApiDataList;
    }
    private List<TcwFinancesApiData> addShipmentEvent(List<TcwFinancesApiData> tcwFinancesApiDataList,ShipmentEvent shipmentEvent
            ,TcwFinancesEventGroups tcwFinancesEventGroups,FinancialEventGroup financialEventGroup
            ,Date postedDate,String code){
        //同个订单多个数据
        for (ShipmentItem shipmentItem : shipmentEvent.getShipmentItemList()) {
            if (shipmentItem.getItemChargeList() != null){
                for (ChargeComponent chargeComponent : shipmentItem.getItemChargeList()) {
                    addTcwF(tcwFinancesApiDataList, code,"ItemChargeList",chargeComponent.getChargeType(), shipmentItem.getSellerSKU(), shipmentItem.getQuantityShipped(),
                            chargeComponent.getChargeAmount().getCurrencyAmount(), financialEventGroup.getFinancialEventGroupId(),
                            shipmentEvent.getAmazonOrderId(), postedDate,null,tcwFinancesEventGroups);
                }
            }

            //promotionalRebatesTax
            BigDecimal promotionalRebatesTax = BigDecimal.ZERO;
            BigDecimal promotionalRebates = BigDecimal.ZERO;
            //促销数据
            if (shipmentItem.getPromotionList() != null) {
                for (int i = 0; i < shipmentItem.getPromotionList().size(); i++) {
                    if (i % 2 == 0){
                        promotionalRebates = promotionalRebates.add(shipmentItem.getPromotionList().get(i).getPromotionAmount().getCurrencyAmount());
                    }else {
                        promotionalRebatesTax = promotionalRebatesTax.add(shipmentItem.getPromotionList().get(i).getPromotionAmount().getCurrencyAmount());
                    }
                }
                //促销费税收
                addTcwF(tcwFinancesApiDataList, code,"PromotionList","promotionalRebatesTax", shipmentItem.getSellerSKU(), shipmentItem.getQuantityShipped(),
                        promotionalRebatesTax
                        , financialEventGroup.getFinancialEventGroupId(),
                        shipmentEvent.getAmazonOrderId(), postedDate,null,tcwFinancesEventGroups);
                //促销费
                addTcwF(tcwFinancesApiDataList, code,"PromotionList","promotionalRebates", shipmentItem.getSellerSKU(), shipmentItem.getQuantityShipped(),
                        promotionalRebates
                        , financialEventGroup.getFinancialEventGroupId(),
                        shipmentEvent.getAmazonOrderId(), postedDate,null,tcwFinancesEventGroups);
            }
            //代缴税收
            if (shipmentItem.getItemTaxWithheldList() != null) {
                BigDecimal marketplaceWithheldTax = BigDecimal.ZERO;
                for (TaxWithheldComponent taxWithheldComponent : shipmentItem.getItemTaxWithheldList()) {
                    for (ChargeComponent chargeComponent : taxWithheldComponent.getTaxesWithheld()) {
                        marketplaceWithheldTax = marketplaceWithheldTax.add(chargeComponent.getChargeAmount().getCurrencyAmount());
                    }
                }
                if (marketplaceWithheldTax.compareTo(BigDecimal.ZERO) != 0){
                    addTcwF(tcwFinancesApiDataList, code,"ItemTaxWithheldList",shipmentItem.getItemTaxWithheldList().get(0).getTaxCollectionModel(), shipmentItem.getSellerSKU(), shipmentItem.getQuantityShipped(),
                            marketplaceWithheldTax, financialEventGroup.getFinancialEventGroupId(),
                            shipmentEvent.getAmazonOrderId(), postedDate,null,tcwFinancesEventGroups);
                }
            }
            //费用组成部分信息的列表
            if (shipmentItem.getItemFeeList() != null) {
                for (FeeComponent feeComponent : shipmentItem.getItemFeeList()) {
                    addTcwF(tcwFinancesApiDataList, code,"ItemFeeList",feeComponent.getFeeType(), shipmentItem.getSellerSKU(), shipmentItem.getQuantityShipped(),
                            feeComponent.getFeeAmount().getCurrencyAmount()
                            , financialEventGroup.getFinancialEventGroupId(),
                            shipmentEvent.getAmazonOrderId(), postedDate,null,tcwFinancesEventGroups);
                }
            }
        }
        return tcwFinancesApiDataList;
    }

    private List<TcwFinancesApiData> getShipmentItemAdjustmentList(List<TcwFinancesApiData> tcwFinancesApiDataList,ShipmentEvent shipmentEvent
                                                    ,TcwFinancesEventGroups tcwFinancesEventGroups,FinancialEventGroup financialEventGroup
                                                    ,Date postedDate,String code){
        //同个订单多个数据
        for (ShipmentItem shipmentItem : shipmentEvent.getShipmentItemAdjustmentList()) {
            if (shipmentItem.getItemChargeAdjustmentList() != null){
                for (ChargeComponent chargeComponent : shipmentItem.getItemChargeAdjustmentList()) {
                    addTcwF(tcwFinancesApiDataList, code,"ItemChargeList",chargeComponent.getChargeType(), shipmentItem.getSellerSKU(), shipmentItem.getQuantityShipped(),
                            chargeComponent.getChargeAmount().getCurrencyAmount(), financialEventGroup.getFinancialEventGroupId(),
                            shipmentEvent.getAmazonOrderId(), postedDate,null,tcwFinancesEventGroups);
                }
            }

            //promotionalRebatesTax
            BigDecimal promotionalRebatesTax = BigDecimal.ZERO;
            BigDecimal promotionalRebates = BigDecimal.ZERO;
            //促销数据
            if (shipmentItem.getPromotionAdjustmentList() != null) {
                for (int i = 0; i < shipmentItem.getPromotionAdjustmentList().size(); i++) {
                    if (i % 2 == 0) {
                        promotionalRebates = promotionalRebates.add(shipmentItem.getPromotionAdjustmentList().get(i).getPromotionAmount().getCurrencyAmount());
                    } else {
                        promotionalRebatesTax = promotionalRebatesTax.add(shipmentItem.getPromotionAdjustmentList().get(i).getPromotionAmount().getCurrencyAmount());
                    }
                }
                //促销费税收
                addTcwF(tcwFinancesApiDataList, code, "PromotionList", "promotionalRebatesTax", shipmentItem.getSellerSKU(), shipmentItem.getQuantityShipped(),
                        promotionalRebatesTax
                        , financialEventGroup.getFinancialEventGroupId(),
                        shipmentEvent.getAmazonOrderId(), postedDate, null, tcwFinancesEventGroups);
                //促销费
                addTcwF(tcwFinancesApiDataList, code, "PromotionList", "promotionalRebates", shipmentItem.getSellerSKU(), shipmentItem.getQuantityShipped(),
                        promotionalRebates
                        , financialEventGroup.getFinancialEventGroupId(),
                        shipmentEvent.getAmazonOrderId(), postedDate, null, tcwFinancesEventGroups);
            }
            //代缴税收
            if (shipmentItem.getItemTaxWithheldList() != null) {
                BigDecimal marketplaceWithheldTax = BigDecimal.ZERO;
                for (TaxWithheldComponent taxWithheldComponent : shipmentItem.getItemTaxWithheldList()) {
                    for (ChargeComponent chargeComponent : taxWithheldComponent.getTaxesWithheld()) {
                        marketplaceWithheldTax = marketplaceWithheldTax.add(chargeComponent.getChargeAmount().getCurrencyAmount());
                    }
                }
                if (marketplaceWithheldTax.compareTo(BigDecimal.ZERO) != 0){
                    addTcwF(tcwFinancesApiDataList, code,"ItemTaxWithheldList",shipmentItem.getItemTaxWithheldList().get(0).getTaxCollectionModel(), shipmentItem.getSellerSKU(), shipmentItem.getQuantityShipped(),
                            marketplaceWithheldTax, financialEventGroup.getFinancialEventGroupId(),
                            shipmentEvent.getAmazonOrderId(), postedDate,null,tcwFinancesEventGroups);
                }
            }
            //费用组成部分信息的列表
            if (shipmentItem.getItemFeeAdjustmentList() != null) {
                for (FeeComponent feeComponent : shipmentItem.getItemFeeAdjustmentList()) {
                    addTcwF(tcwFinancesApiDataList, code,"ItemFeeList",feeComponent.getFeeType(), shipmentItem.getSellerSKU(), shipmentItem.getQuantityShipped(),
                            feeComponent.getFeeAmount().getCurrencyAmount()
                            , financialEventGroup.getFinancialEventGroupId(),
                            shipmentEvent.getAmazonOrderId(), postedDate,null,tcwFinancesEventGroups);
                }
            }
        }
        return tcwFinancesApiDataList;
    }

    /**
     * 批量导入财务事件刷新
     * @return
     */
    @Override
    public R importInfo(String rows, Long menuId){
        synchronized (lock) {
            try {
                JSONArray JA = JSON.parseArray(rows);
                for (int i = 0; i < JA.size(); i++) {
                    JSONObject JO = JA.getJSONObject(i);
                    // 临界区代码
                    Calendar cal = Calendar.getInstance();
                    int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); // 获取当前是星期几
                    int weekOfMonth = cal.get(Calendar.WEEK_OF_MONTH); // 获取当前是月份的第几周

                    if (dayOfWeek == Calendar.SUNDAY && weekOfMonth == 1) {
                        return R.error("今天是每月第一周的星期天不允许重新刷新");
                    }
                    if (JO.get("financesEventGroupsYf") == null || JO.get("year") == null || JO.get("companyID") == null) {
                        return R.error("数据不全,核实后再操作!");
                    }
                    boolean variable = true;
                    while (variable) {
                        for (Map.Entry<String, Integer> e : THREADF_MAP.entrySet()) {
                            if (e.getValue() == 1) {
                                continue;
                            } else if (e.getValue() == 0) {
                                THREADF_MAP.put(e.getKey(), 1);
//								 开启线程
                                int finalI = i;
                                Thread t = new Thread(() -> {

                                    String financesEventGroupsYf = JO.get("financesEventGroupsYf").toString();
                                    String year = JO.get("year").toString();
                                    String companyID = JO.get("companyID").toString();
                                    int yearint = Integer.parseInt(year);
                                    int month = Integer.parseInt(financesEventGroupsYf);
                                    //月份第一天
                                    Calendar calendar = Calendar.getInstance();
                                    calendar.set(yearint, month - 1, 1);
                                    calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
                                    //月份最后一天
                                    Calendar calendar1 = Calendar.getInstance();
                                    calendar1.set(yearint, month - 1, 20);
                                    calendar1.set(Calendar.DAY_OF_MONTH, calendar1.getActualMaximum(Calendar.DAY_OF_MONTH));

                                    calendar.set(Calendar.HOUR_OF_DAY, 00);
                                    calendar.set(Calendar.MINUTE, 00);
                                    calendar.set(Calendar.SECOND, 00);

                                    calendar1.set(Calendar.HOUR_OF_DAY, 23);
                                    calendar1.set(Calendar.MINUTE, 59);
                                    calendar1.set(Calendar.SECOND, 59);

                                    Date startTime = calendar.getTime();
                                    String startTimeStr = DateUtils.convertDateToTDate(startTime);
                                    Date endTime = calendar1.getTime();
                                    String endTimeStr = DateUtils.convertDateToTDate(endTime);

                                    //删除表中数据
                                    diySqlMapper.deleteFinancesApiData();
                                    //查询所有店铺信息
                                    List<Map<String, Object>> tpAmazonSellerList = new TpAmazonSeller()
                                            .addLeftJoin("TP_AmazonRegion tar on tar.Code = A.regionCode")//平台地区
                                            .addField("tar.AwsRegion awsRegion,tar.AmazonServiceUrl amazonServiceUrl,tar.code amazonRegionCode")
                                            .where("A.authorizeState = '已授权'" + "AND A.vgsbm = '" + companyID +"'")
                                            .setStatus(1)
                                            .queryMap();
                                    JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(tpAmazonSellerList));
                                    for (int j = 0; j < jsonArray.size(); j++) {
                                        JSONObject jsonObject = jsonArray.getJSONObject(j);
                                        TpAmazonSeller tpAmazonSeller = new TpAmazonSeller().setSellerId(jsonObject.get("sellerId").toString()).queryFirst();
                                        ApiResponse apiResponse = getFinancesApi(jsonObject, startTimeStr, endTimeStr);
                                        if (apiResponse.getCode() == 500) {
                                            apiLogService.addApiLog("Amazon", "GetFinancesApiWeb", "ECP_API定时获取亚马逊财务事件信息出错，条件queryParams：" + JSON.toJSONString(jsonObject), "店铺:" + jsonObject.get("sellerName").toString(), apiResponse.getCode(), apiResponse.getMessage());
                                        }
                                        logger.info("***********每月定时新增财务目录GetFinancesApiWeb，结束***********");

                                        logger.info("***********每月定时新增财务事件明细GetFinancesInfoWeb，开始***********");
                                        apiResponse = getFinancesInfo(tpAmazonSeller, startTimeStr, endTimeStr);
                                        if (apiResponse.getCode() == 500) {
                                            apiLogService.addApiLog("Amazon", "GetFinancesInfoWeb", "ECP_API定时获取亚马逊财务事件信息出错，条件queryParams：" + JSON.toJSONString(jsonObject), "店铺:" + jsonObject.get("sellerName").toString(), apiResponse.getCode(), apiResponse.getMessage());
                                        }
                                        logger.info("***********每月定时新增财务事件明细GetFinancesInfoWeb，结束***********");
                                        System.out.println("i="+ finalI);
                                        }
                                    THREADF_MAP.put(e.getKey(), 0);
                                });
                                t.start();
                                Thread.sleep(1000L);
                            }
                            variable = false;
                            break;
                        }
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        return R.ok("导入成功！");
    }
}
